【问题标题】:Chrome Extension: Send Message from Background to Injected ScriptChrome 扩展:从后台向注入脚本发送消息
【发布时间】:2013-06-27 01:30:24
【问题描述】:

我目前正在使用 Chrome 扩展程序,但找不到方便的解决方案将消息从后台上下文(我们称之为 BG)发送到注入脚本的上下文(让称之为INJ)。将消息从 INJ 发送到 BG 就像一个魅力。但我希望 BG 执行 XMLHttpRequest,这可能需要一些时间,所以我想将此请求的评估发送给 INJ

很遗憾,我不允许在 INJ 的上下文中注册侦听器。所以我能想到的最佳解决方案包括:

  • INJBG发送消息,触发XMLHttpRequest
  • 请求一返回BG就在本地存储请求的结果
  • INJ 反复向 BG 发送更多消息,询问结果,除非 BG 以结果回答。

可能是这样的:

INJ

function whaitForResult ()
{
  chrome.runtime.sendMessage ({method: "getResult"}, function (response)
  {
    if (response.finished === "true")
      // request finished, lets go on
    else
      setTimeout(whaitForResult, 100);
  }
}
chrome.runtime.sendMessage({method : "triggerRequest"}, function(response) {});
whaitForResult ();

背景

chrome.runtime.onMessage.addListener (function(request, sender, sendResponse)
{
  if (request.method == "triggerRequest")
  {
    // startXMLHttpRequest ();
    sendResponse ({});
    return true;
  }
  else if (request.method == "getResult")
  {
    if (finishedXMLHttpRequest ())
      sendResponse ({finished:"true", result: resultFromXMLHttpRequest ()});
    else
      sendResponse ({finished:"false"});
    return true;
  }
});

我想这应该可行,但在我看来它很混乱。所以我的问题是:有没有一种方便的方法可以向注入的脚本发送消息?

如果我的扩展概念很垃圾,请提出替代方案。但是要执行XMLHttpRequest,我需要来自localStorage 的一些变量,并且由于这些数据非常敏感,我不想将这些变量传递给INJ 的上下文。因此,在 INJ 中执行XMLHttpRequest 不是一种选择。

【问题讨论】:

    标签: javascript google-chrome-extension xmlhttprequest message-passing


    【解决方案1】:

    在我继续之前,我想指出你只是在处理一个普通的内容脚本,而不是一个“注入脚本”(根据my definition)。

    不要在第一次请求时发送响应 (sendResponse({}))。而是在响应完成后调用sendResponse

    // Content script
    chrome.runtime.sendMessage({method: "getResultForRequest"}, function(response) {
    
    });
    // Background page
    chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
        if (request.method == "getResultForRequest") {
            $.ajax({success: sendResponse}); // Example
            return true;
        }
    });
    

    正如该答案顶部所说,您要处理的不是注入脚本,而是内容脚本。 script execution environment of the content script 和页面是严格分开的,所以页面无法读取变量。换句话说,你的前提是有缺陷的;可以将凭据从后台页面传递到内容脚本。

    我建议不要使用 localStorage,而是使用 chrome.storage API。此异步 API 允许内容脚本直接读取扩展存储的持久变量。因此,您不再需要背景或事件页面。更详细的对比和例子,我参考this answer

    注意:在两种情况下让后台页面处理 XHR 是有意义的:

    • 页面的内容安全策略阻止目标 URL (this affects Chrome extensions)
    • 当前页面通过 https 提供,而请求的资源通过 http 提供。混合使用 http 和 https 会改变挂锁的外观,应尽可能避免。

    但除此之外,我建议使用 chrome.storage API 并在您的内容脚本中执行跨域 http 请求。

    【讨论】:

    • 谢谢,它有效!也非常感谢补充:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-04-16
    • 2014-02-04
    • 2014-11-27
    • 1970-01-01
    • 1970-01-01
    • 2014-11-23
    相关资源
    最近更新 更多