Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Chrome extension - Message Passing

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>
like image 659
Felipe Barreiros Avatar asked Jun 08 '10 15:06

Felipe Barreiros


1 Answers

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.

like image 126
Mohamed Mansour Avatar answered Nov 28 '22 17:11

Mohamed Mansour