Chrome extension - Message Passing

大憨熊 提交于 2019-12-18 13:34:49

问题


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>

回答1:


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.



来源:https://stackoverflow.com/questions/2998775/chrome-extension-message-passing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!