javascript - 如何使用 Firefox 插件读取特定 URL 的 html 内容?

标签 javascript html firefox-addon

我想创建一个插件,它将加载特定网址的 html 内容并保存该页面的特定行,然后移动到该网址。我在 Mozila.org 上阅读了很多有关网页内容的内容,但我不明白如何阅读 html 内容。

最佳答案

这是一个执行 XHR 请求的简单代码片段,没有 cookie。不用担心跨域,因为您是从特权范围运行的,这意味着您不是在网站中编码,而是作为 Firefox 插件进行编码。

var {Cu: utils, Cc: classes, Ci: instances} = Components;
Cu.import('resource://gre/modules/Services.jsm');
function xhr(url, cb) {
    let xhr = Cc["@mozilla.org/xmlextras/xmlhttprequest;1"].createInstance(Ci.nsIXMLHttpRequest);

    let handler = ev => {
        evf(m => xhr.removeEventListener(m, handler, !1));
        switch (ev.type) {
            case 'load':
                if (xhr.status == 200) {
                    cb(xhr.response);
                    break;
                }
            default:
                Services.prompt.alert(null, 'XHR Error', 'Error Fetching Package: ' + xhr.statusText + ' [' + ev.type + ':' + xhr.status + ']');
                break;
        }
    };

    let evf = f => ['load', 'error', 'abort'].forEach(f);
    evf(m => xhr.addEventListener(m, handler, false));

    xhr.mozBackgroundRequest = true;
    xhr.open('GET', url, true);
    xhr.channel.loadFlags |= Ci.nsIRequest.LOAD_ANONYMOUS | Ci.nsIRequest.LOAD_BYPASS_CACHE | Ci.nsIRequest.INHIBIT_PERSISTENT_CACHING;
    //xhr.responseType = "arraybuffer"; //dont set it, so it returns string, you dont want arraybuffer. you only want this if your url is to a zip file or some file you want to download and make a nsIArrayBufferInputStream out of it or something
    xhr.send(null);
}

此代码段的示例用法:

var href = 'http://www.bing.com/'
xhr(href, data => {
    Services.prompt.alert(null, 'XHR Success', data);
});

关于javascript - 如何使用 Firefox 插件读取特定 URL 的 html 内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25109620/

相关文章:

javascript - React 组件正在渲染,然后消失

asp.net - 在页面加载时使用 JavaScript 填充文本框

html - child 比最大高度的 parent 大。溢出没有影响

Firefox Addon SDK 中内容脚本内的 JQuery UI

javascript - 从 ReactJS 中导入的函数更改类状态

JavaScript:使用reduce函数的句子变体

Firefox 扩展设置代理身份验证

javascript - 火狐插件。如何真正下载图像/文件?

javascript - 来自托管文件的 Canvas 图像 src

css - Flexbox 中的 Bootstrap 4 文本中心不起作用