javascript - Chrome 扩展程序在执行需要 4/5 秒的代码后进行 Web 请求重定向

标签 javascript google-chrome redirect google-chrome-extension

我正在尝试创建一个 Chrome 扩展程序,它执行一些代码(大约需要 4 秒),然后执行回调将用户重定向到页面。但是,使用以下代码不会发生重定向:

 chrome.webRequest.onBeforeRequest.addListener(function(details) {
    functionThatTakes4Seconds(function(){
            return {
                redirectUrl: redirect
            };
    );
}, {
    urls: ["url.com"]
}, ["blocking"]);

当我不运行需要 4 秒的函数时,重定向会起作用:

 chrome.webRequest.onBeforeRequest.addListener(function(details) {
            return {
                redirectUrl: redirect
            };
}, {
    urls: ["url.com"]
}, ["blocking"]);

是否超时?有解决方法吗?

最佳答案

您无法从异步代码返回

如果确实返回阻塞响应,则必须同步返回; Chrome 不会等待,您也不会收到异步调用的回调。

If the optional opt_extraInfoSpec array contains the string 'blocking' (only allowed for specific events), the callback function is handled synchronously. That means that the request is blocked until the callback function returns.

例如如果您的代码需要 4 秒才能完成但是同步的,您可以从中返回值并执行以下操作:

chrome.webRequest.onBeforeRequest.addListener(function(details) {
  return {
    redirectUrl: functionThatTakes4Seconds() // must return something
  };
}, {
    urls: ["url.com"]
}, ["blocking"]);

但是您无法执行异步调用并让 Chrome 等待它。

Messaging相比:在那里你会得到一个回调 sendResponse ,你可以异步调用它。但不在这里。

关于javascript - Chrome 扩展程序在执行需要 4/5 秒的代码后进行 Web 请求重定向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28383739/

相关文章:

javascript - contenteditable div 中的 n gram 突出显示

android - 在安装了 Google Play 的 Genymotion 模拟器中运行 Chrome 应用程序时遇到问题

javascript - Chrome 扩展程序发送 key

javascript - 使用 ng click 完全删除或删除元素以及数组内的数据

javascript - socket.io 动态命名空间

google-chrome - 是否可以开发不是 chrome 扩展的 Chrome 书签管理器应用程序,即独立于 chrome 浏览器运行的应用程序?

.htaccess - 拒绝访问文件夹内的文件但允许 REST API

javascript - 基于 URL 的重定向 - JavaScript

apache - www 和 https 重定向未按预期工作

javascript - D3 指令 - 路径值无效导致错误