【问题标题】:Mozilla addon loading too late to block a resourceMozilla 插件加载太晚而无法阻止资源
【发布时间】:2020-06-02 03:30:37
【问题描述】:

我正在尝试取消从 studio.code.org 到 www.google.com/jsapi 的请求,以帮助加快页面加载速度。在我的语言环境中,谷歌被阻止,但浏览器在放弃之前等待 75 秒。我想通过阻止请求来防止延迟(并且页面似乎在没有 jsapi 的情况下工作正常)。

我按照https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/webRequest/onBeforeRequest 的示例安装了插件。我包含了一个 console.log 语句来查看我的代码被调用,但它仅在浏览器等待另外 75 秒以尝试加载我希望阻止的资源后才显示。

如果这不起作用,我愿意接受其他方法。

manifest.json:

{
  "manifest_version": 2,
  "name": "cancel-google",
  "version": "1.0",

  "permissions": [
    "webRequest",
    "webRequestBlocking"
  ],

  "content_scripts": [
    {
      "matches": ["https://studio.code.org/*"],
      "js": ["cancel-google.js"]     
    } 
  ]
}

取消-google.js:

// match pattern for the URLs to block
var pattern = "*www.google.com/jsapi";
console.log("cancelator script loaded");

// cancel function returns an object
// which contains a property `cancel` set to `true`
function cancel(requestDetails) {
  console.log("Cancelling: " + requestDetails.url);
  return {cancel: true};
}

// add the listener,
// passing the filter argument and "blocking"
browser.webRequest.onBeforeRequest.addListener(
  cancel,
  {urls: [pattern]},
  ["blocking"]
);

【问题讨论】:

  • 顺便说一句,你为什么不为此使用广告拦截器?
  • 我尝试了一些 mozilla.org 推荐的广告拦截器,其中至少有一个提到了 google.com/jsapi 的名称,但它们并没有真正帮助加载时间。

标签: request firefox-addon mozilla firefox-addon-webextensions


【解决方案1】:

Smile4ever 的回答是正确的,但我发现我的原始代码存在一些其他问题。

首先 - 我的原始内容脚本的“时间”问题是一个红鲱鱼。原内容脚本虽然会写入页面的日志,但对加载资源没有影响。相同的脚本,作为后台脚本,不会将任何内容(我注意到)写入控制台日志,但它会起作用。

第二 - 后台脚本需要比我最初拥有的更多权限(比mozilla.org link 中描述的更多)。

"permissions": [
  "http://*/*",
  "https://*/*",
  "webRequest",
  "webRequestBlocking" ]

以上权限足够/过多;您还可以将"http(s)://*/*" 替换为请求资源和要阻止的资源的页面的实际网址。

【讨论】:

    【解决方案2】:

    cancel-google.js 应该作为后台脚本加载,对于大多数 WebExtension API 来说都是如此。

    {
        "name": "Your Addon",
        "manifest_version": 2,
        "background": {
            "scripts": ["cancel-google.js"]
        }
    }
    

    那么它应该可以工作了。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-10-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多