在阻塞 webRequest 处理程序中使用异步调用

use*_*880 3 javascript firefox firefox-addon firefox-addon-webextensions

概括

我正在使用browser.webRequest.onBeforeRequest处理程序。我需要阻止 webRequest 直到我从处理程序中对异步方法的调用返回信息。我怎样才能做到这一点?

细节

首先,我为这么长的问题道歉。但我希望有人可以提供帮助。

我有一个嵌入式扩展,其中包含一个browser.webRequest.onBeforeRequest(我现在需要使用嵌入式扩展来处理一些 SDK 遗留代码)。

browser.webRequest.onBeforeRequest回调函数连接到一个SDK扩展,并指示它执行某些功能。从任务完成后,SDK 会向 webextension 发送回复。我使用awaitinbrowser.runtime.sendMessage来确保我停止执行,直到我得到 SDK 的回复。要使用await,我不得不使用async(但实际上我不想要async功能)。当我不使用 时await,我只会在循环完成所有迭代后从 SDK 得到回复,而不是每次迭代。

下面的示例代码包含许多用于调试的控制台消息,只是为了监视执行。

问题是:我没有得到可靠的结果。在某些情况下(不是全部),http 请求在 SDK 代码生效之前就发出了。我可以识别这一点,因为请求属性必须受 SDK 代码的影响。控制台按预期显示执行顺序。但是,http 请求不受 SDK 的影响(在某些情况下)。

在这个简单的例子中,SDK 只是向 webextension 发送消息,但假设它执行一些功能,读/写操作等。所有 SDK 任务必须在请求发出之前完成。

我真正需要的是保证在执行所有 SDK 代码之前 Web 请求不会发出。

参考 MDN 文档,它说 browser.webRequest.onBeforeRequest 是一个async函数。我想知道这是否是问题的根源?如果是这样,如何强制它同步?

embedding-extension [directory]
    - index.js
    - package.json
    - webextension [directory]
       - main.js
       - manifest.json
Run Code Online (Sandbox Code Playgroud)

1)package.json

{
  "title": "testhybrid",
  "name": "testhybrid",
  "version": "0.0.1",
  "description": "A basic add-on",
  "main": "index.js",
  "author": "",
  "engines": {
    "firefox": ">=38.0a1",
    "fennec": ">=38.0a1"
  },
  "license": "MIT",
  "hasEmbeddedWebExtension": true,
  "keywords": [
    "jetpack"
  ]
}
Run Code Online (Sandbox Code Playgroud)

2)index.js

const webExtension = require("sdk/webextension");
console.log("in SDK: inside embedding extension");

// Start the embedded webextension
  webExtension.startup().then(api => {
    const {browser} = api;
    browser.runtime.onMessage.addListener((msg, sender, sendReply) => {
      if (msg == "send-to-sdk") {
         console.log("in SDK: message from webExt has been received");
        sendReply({
          content: "reply from SDK"
        }); //end send reply
      }//end if

    }); //end browser.runtime.onMessage

  }); //end webExtension.startup
Run Code Online (Sandbox Code Playgroud)

3)manifest.json

{
  "manifest_version": 2,
  "name": "webExt",
  "version": "1.0",
  "description": "No description.",
  "background": {
    "scripts": ["main.js"]
  },

  "permissions": [
    "activeTab",
    "webRequest",
  "<all_urls>"
],

"browser_action": {
  "default_icon": {
    "64": "icons/black-64.png"
  },
  "default_title": "webExt"
}
}
Run Code Online (Sandbox Code Playgroud)

4)main.js

var flag=true;
async function aMethod() {
  console.log("in webExt: inside aMethod");
  for(var x=0; x<2; x++)
  {
    console.log("loop iteration: "+x);
    if(flag==true)
      {
        console.log("inside if");
        console.log("will send message to SDK");
        const reply = await browser.runtime.sendMessage("send-to-sdk").then(reply => {
        if(reply)
        {
          console.log("in webExt: " + reply.content);
        }
        else {
           console.log("<<no response message>>");
        }
        });
      }//end if flag

    else
      {
        console.log("inside else");
      }//end else
  }//end for
}

browser.webRequest.onBeforeRequest.addListener(
  aMethod,
  {urls: ["<all_urls>"],
   types: ["main_frame"]}
);
Run Code Online (Sandbox Code Playgroud)

Mak*_*yen 5

webRequest.onBeforeRequest文件指出(强调我的):

要取消或重定向请求,首先"blocking"extraInfoSpec数组参数中包含addListener(). 然后,在侦听器函数中,返回一个BlockingResponse对象,设置适当的属性:

  • 要取消请求,请包含cancel值为 true的属性。
  • 要重定向请求,请包含一个属性redirectUrl,该属性的值设置为要重定向到的 URL。

从Firefox 52开始,而不是返回BlockingResponse,听者可以返回一个承诺,其与解决BlockingResponse。这使侦听器能够异步处理请求。

您似乎没有执行上述任何操作。因此,该事件是完全异步处理的,不可能将请求延迟到您的处理程序返回。换句话说,正如目前所写,您webRequest.onBeforeRequest对 webRequest 绝对没有影响。您的处理程序只是通知 webRequest 正在处理中。

要完成您的愿望,请将请求延迟到您执行一些异步操作之后,您需要:

  1. 添加"webRequestBlocking"到您的manifest.json权限:

      "permissions": [
        "activeTab",
        "webRequest",
        "webRequestBlocking",
        "<all_urls>"
      ],
    
    Run Code Online (Sandbox Code Playgroud)
  2. "blocking"extraInfoSpec数组参数传递给addListener()

    browser.webRequest.onBeforeRequest.addListener(
      aMethod,
      {urls: ["<all_urls>"],
       types: ["main_frame"]},
      ["blocking"]
    );
    
    Run Code Online (Sandbox Code Playgroud)
  3. 从您的处理程序返回一个 Promise,它用一个来解析BlockingResponse

    function aMethod() {
        //Exactly how this is coded will depend on exactly what you are doing.
        var promises = [];
        console.log("in webExt: inside aMethod");
        for (var x = 0; x < 2; x++) {
            console.log("loop iteration: " + x);
            if (flag == true) {
                console.log("inside if");
                console.log("will send message to SDK");
                promises.push(browser.runtime.sendMessage("send-to-sdk").then(reply => {
                    if (reply) {
                        console.log("in webExt: " + reply.content);
                    } else {
                        console.log("<<no response message>>");
                    }
                });
            } else {
                console.log("inside else");
            }
        }
        return Promise.all(promises).then(function(){
            //Resolve with an empty Object, which is a valid blockingResponse that permits
            //  the webRequest to complete normally, after it is resolved.
            return {};
        });
    }
    
    Run Code Online (Sandbox Code Playgroud)