【问题标题】:Chrome extension: communication between background and content scriptsChrome 扩展:后台和内容脚本之间的通信
【发布时间】:2017-09-09 01:38:22
【问题描述】:

我需要从后台脚本执行内容脚本,并从后台脚本向内容脚本发送几个参数。我探索了几个像这样的帮助页面...

https://developer.chrome.com/extensions/content_scripts#pi

...但仍然不知道如何组织它。在一个 Firefox 扩展中,我做了以下事情:

背景脚本摘录:

browser.tabs.executeScript({
              file: "content/login.js"
            }).then(messageContent).catch(onError)
}

function messageContent() {

    var gettingActiveTab = browser.tabs.query({active: true, currentWindow: true});

    gettingActiveTab.then((tabs) => {
          browser.tabs.sendMessage(tabs[0].id, {loginUserName: loginUserName, loginPassword: loginPassword});
                    });
}

内容脚本摘录:

function justDoTheJob(request, sender, sendResponse) {

    var doc = window.content.document;

    doc.getElementById("loginUserName").value = request.loginUserName;
    doc.getElementById("loginPassword").value = request.loginPassword;

}

browser.runtime.onMessage.addListener(justDoTheJob);

但是当我在 Chrome 中执行类似操作时,我会得到以下信息:

响应 tabs.query 时出错:TypeError: Cannot read property 'then' of undefined at Object.callback

所以看起来我使用了错误的语法甚至是错误的结构。能否请您给我一些有关如何正确执行此操作的线索?

谢谢, 浣熊

【问题讨论】:

  • chrome API 不是基于 Promise 的,因此您需要切换到回调或使用 polyfill
  • 谢谢。那么如何使用回调将一些参数从后台脚本发送到内容脚本呢?有什么例子吗?

标签: javascript google-chrome google-chrome-extension


【解决方案1】:

正如@qwOxxOm 在 cmets 中指出的那样,您需要在 Chrome 中使用回调,例如,不要附加 then(),而是将 then 中的函数移动到调用本身的参数链中。否则它的使用方式几乎相同:

chrome.tabs.executeScript({file: "content/login.js"}, myCallback);

function callback(result) {
  // handle result here
}

或喜欢:

function messageContent() {
  chrome.tabs.query({active: true, currentWindow: true}, (tabs) => {
     // sendMessage here
  })
}

等等

错误处理有点不同,因为您会检查 lastError 而不是对其使用回调。

您还可以为 Firefox 使用 chrome 命名空间(在您需要考虑的某些方面,两个浏览器/命名空间之间存在一些差异)。

【讨论】:

    猜你喜欢
    • 2012-07-29
    • 1970-01-01
    • 2018-08-15
    • 1970-01-01
    • 1970-01-01
    • 2011-11-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多