javascript Chrome 扩展 - 从弹出窗口到内容脚本的消息传递
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6108906/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Chrome Extension - Message Passing from Popup to Content Script
提问by ktross
I'm trying to pass data from a popup to a content script, but I'm not having any luck. I got it to work the other way around (content -> popup) though. All I want to do is enter text into an input located in the popup and click a submit button which would insert that text into the dom of a web page.
我正在尝试将数据从弹出窗口传递到内容脚本,但我没有任何运气。我让它以另一种方式工作(内容 - >弹出)。我想要做的就是在位于弹出窗口的输入中输入文本,然后单击提交按钮,该按钮会将文本插入到网页的 dom 中。
This is what I have:
这就是我所拥有的:
popup.html
弹出窗口.html
chrome.extension.sendRequest({action:'start'}, function(response) {
console.log('Start action sent');
});
contentscript.js
内容脚本.js
function startExtension() { console.log('Starting Extension'); }
function stopExtension() { console.log('Stopping Extension'); }
function onRequest(request, sender, sendResponse) {
if (request.action == 'start')
startExtension()
else if (request.action == 'stop')
stopExtension()
sendResponse({});
}
chrome.extension.onRequest.addListener(onRequest);
采纳答案by Diogo Gomes
You need to specify to which tab to send to. Like this:
您需要指定要发送到哪个选项卡。像这样:
chrome.tabs.sendMessage(tab.id, {action:'start'}, function(response) {
console.log('Start action sent');
});
If you don't know which is the tab, you can either send to all (probably a bad idea) or make the tab send info first.
如果您不知道哪个是选项卡,您可以发送给所有人(可能是个坏主意)或让选项卡先发送信息。
For more information check this page: Message Passing.
有关更多信息,请查看此页面:消息传递。