在浏览器窗口中高效滚动管道输出

Efficient scrolling of piped output in a browser window

本文关键字:滚动 管道 输出 高效 浏览器 窗口      更新时间:2023-09-26

我有一个自定义浏览器插件(使用FireBreath构建),它将调用用户机器上的本地进程,并通过管道将stdout发送回浏览器,为此,我通过popen()调用运行该进程,当我从管道中读取数据时,我会触发一个JSAPI事件并将其发送回浏览器。

在浏览器中,我将输出作为预先格式化的文本附加到div中,并告诉div滚动到底部。

浏览器插件中的代码:

FILE* in;
if(!(in = _popen(command_string, "r")))
{
    return NULL;
}
while(fgets(buff, sizeof(buff), in)!=NULL)
{
    send_output_to_browser(buff);
}

HTML&Javascript/jQuery:

<pre id="sync_status_window" style="overflow:scroll">
    <span id="sync_output"></span>
</pre>

var onPluginTextReceived = function (text)
{
    $('#sync_output').append(text);   
    var objDiv = document.getElementById('sync_status_window');
    objDiv.scrollTop = objDiv.scrollHeight;
}

这种方法适用于我需要的浏览器(这是一种有限使用的内部工具),但它的滞后性令人沮丧。我的过程通常在输出窗口滚动结束前30-60秒左右结束。那么,我该如何提高效率呢?有没有更好的方法将这些文本通过管道发送回浏览器?

我认为有两种优化潜力:

  1. 保持对你的pre和span的引用,你不断重复dom树搜索,成本相当高
  2. 分块输出-在C端(最好)或JS上侧面

对于快速破解(不需要删除对jquery的依赖,这应该完成)可能看起来像

//Higher or global scope
var pluginBuffer=[];
var pluginTimeout=false;
var sync_status_window=document.getElementById('sync_status_window');
function onPluginTextReceived(text)
{
    pluginBuffer[pluginBuffer.length]=text;
    if (!pluginTimeout) pluginTimeout=window.SetTimeout('onPluginTimer();',333);
}
function onPluginTimer()
{
    var txt=pluginBuffer.join('');
    pluginBuffer=[];
    pluginTimeout=false;
    $('#sync_output').append(text);
    sync_status_window.scrollTop = sync_status_window.scrollHeight;
 }

适应您的需求,我选择333ms进行3次更新/秒