简体   繁体   English

Chrome扩展程序:后台脚本和内容脚本之间的通信

[英]Chrome extension: communication between background and content scripts

I need to execute a content script from a background script with sending a couple of parameters from the background script to the content one. 我需要从后台脚本执行内容脚本,并从后台脚本向内容脚本发送几个参数。 I explored a couple of help pages like this one ... 我浏览了几个这样的帮助页面...

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

... but still have no idea how to organize it. ...但是仍然不知道如何组织它。 In a Firefox extension, I did the following: 在Firefox扩展程序中,我执行了以下操作:

background script excerpt: 后台脚本摘录:

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});
                    });
}

content script excerpt: 内容脚本摘录:

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);

But when I do something like that in Chrome, I get the following: 但是,当我在Chrome中执行类似操作时,会得到以下信息:

Error in response to tabs.query: TypeError: Cannot read property 'then' of undefined at Object.callback 响应tabs.query时出错:TypeError:无法读取Object.callback上未定义的属性'then'

So it looks like I am using a wrong syntax or even wrong structure at all. 因此,看来我使用的是错误的语法甚至是错误的结构。 Could you please give me some clue on how to do it properly? 您能给我一些有关如何正确执行的线索吗?

Thanks, Racoon 谢谢浣熊

As @qwOxxOm points out in comments, you need to use callbacks in Chrome, for example, instead of appending with then() , move the function inside then to the argument chain of the call itself. 正如@qwOxxOm在注释中指出的那样,例如,您需要在Chrome中使用回调,而不是在then()后面附加函数, then将函数移到调用本身的参数链中。 Otherwise it's used pretty much the same way: 否则,它的使用方式几乎相同:

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

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

or like: 或类似:

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

etc. 等等

Error handling is a bit different as you would check lastError instead of using a callback for it. 错误处理有些不同,因为您将检查lastError而不是对其使用回调。

You can also use the chrome namespace for Firefox (there are some differences between the two browsers/namespaces in some areas you need to take into consideration). 您也可以为Firefox使用chrome名称空间(两种浏览器/名称空间在某些方面需要有所区别)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM