Chrome扩展程序 - 消息传递 [英] Chrome extension - Message Passing
问题描述
基本上,如果OptionsPage上的一个复选框被设置了,那么我们就可以在OptionsPage上设置一个信息来改变我的扩展的行为。为true,扩展运行,否则它不会。
为了测试的目的,我在background.html上返回true,但仍然无效。
你们能帮我一下吗?感谢!
正在注入页面的代码:
if(chrome.extension.sendRequest()=='true')
alert(checkbox set to true);
else
alert(it is disabled);
background.html
< script>
pre>
chrome.extension.onRequest.addListener(function(){
return true;
}
< / script>
解决方案如果您有选项页面,并且您想要与后台页面,您只需执行 chrome.extension。 getBackgroundPage()
选项页面与后台页面进行通信
options.html
$ bvar bkg = chrome.extension.getBackgroundPage()
bkg.startExtension();
bkg.stopExtension();
background.html
function startExtension(){
conso le.log('Starting Extension');
function stopExtension(){
console.log('Stopping Extension');
}
与后台页面通信的内容脚本
当您提到被注入页面的代码是指任何网站?如果是这样,您需要使用内容脚本与消息传递。为此,您可以这样做。
content_script.js
<$ p $ $ {code> chrome.extension.sendRequest({action:'start'},function(response){
console.log('Start action sent');
});
background.html
函数onRequest(request,sender,sendResponse){
if(request.action =='start')
startExtension()
else if(request.action =='stop')
stopExtension()
sendResponse({});
};
chrome.extension.onRequest.addListener(onRequest);
在任何情况下,消息传递对任何进入扩展的人来说都是一个很好的解读。
I'm trying to get the info that is set on the Options Page to alter the behavior of my extension.
Basically, if a checkbox on OptionsPage is set to true, the extension runs, otherwise it doesn't. I'm returning true on the background.html for testing purposes, but still, it doesn't work.
Would you guys help me out? Thanks!
Code being injected to the page:
if(chrome.extension.sendRequest() == 'true')
alert("checkbox set to true");
else
alert("it is disabled");
background.html
<script>
chrome.extension.onRequest.addListener(function(){
return true;
}
</script>
If you have an options page and you want to communicate to the background page, you can simply do, chrome.extension.getBackgroundPage()
Options Page communicating to the Background Page
options.html
var bkg = chrome.extension.getBackgroundPage()
bkg.startExtension();
bkg.stopExtension();
background.html
function startExtension() {
console.log('Starting Extension');
}
function stopExtension() {
console.log('Stopping Extension');
}
Content Script communicating to the Background Page
When you are referring to "Code being injected to the page" is that any website? If so, you would need to use a content script with Message Passing. To do so, you can do this.
content_script.js
chrome.extension.sendRequest({action:'start'}, function(response) {
console.log('Start action sent');
});
background.html
function onRequest(request, sender, sendResponse) {
if (request.action == 'start')
startExtension()
else if (request.action == 'stop')
stopExtension()
sendResponse({});
};
chrome.extension.onRequest.addListener(onRequest);
In any case, message passing is a good read for anyone coming into extensions.
这篇关于Chrome扩展程序 - 消息传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!