Chrome extension Send message from background to content script

I'm new to chrome extensions, and after spending hours on this issue, I decided to ask:

My background script only sends a message to my script content after I reload the extension and quickly go to the tab. Other wise nothing happens.

{ "name": "Fixes", "version": "2", "manifest_version": 2, "description": "SomeFixes", "permissions": ["tabs", "http://*/*", "https://*/*", "storage"], "options_page": "options.html", "background": { "persistent": false, "scripts": ["background.js"] }, "content_scripts": [ { "matches": ["<all my urls>"], "js": ["jquery1.7.js", "helper.js"] } ], "browser_action": { "default_icon": "icon.png", "default_popup": "options.html" } } 

Background.js

 chrome.tabs.query({active: true, currentWindow: true}, function(tabs){ chrome.tabs.sendMessage(tabs[0].id, {type:"test"}, function(response) {}); }); 

helper.js

 jQuery(document).ready(function() { //Get allowed functions chrome.extension.onMessage.addListener(function(msg, sender, sendResponse) { if(msg.type == "test"){ alert("test received"); }); 

The warning field appears only after rebooting the extension and quickly switching to the tab in which the warning window should appear.

So, I thought that background.js should load every time I reload the tab. But now it loads only once, and if I'm not on this tab, it loads before helper.js is ready to send a response. This is my theory. But, as I said, I'm new to this, and I'm struggling to figure out how this works.

Ultimately, what I'm trying to accomplish is that the user saves some parameters that will be loaded by default every time the page loads. Saving settings on the options page works fine. The popup page also works as it should. I just can't load the default options because I can't get the message on the script page.

+4
source share
1 answer

The background page will be launched every time the extension is loaded, and since it is an event page, it is unloaded, and any event for it will execute your code again. Try to do it like this instead

helper.js

 chrome.extension.sendMessage({text:"getStuff"},function(reponse){ //This is where the stuff you want from the background page will be if(reponse.type == "test") alert("Test received"); }); 

background.js

 chrome.extension.onMessage.addListener(function(message,sender,sendResponse){ if(message.text == "getStuff") sendResponse({type:"test"}); }); 

Thus, the content script starts the flow of information, so you know for sure that it is ready to accept it.

+7
source

All Articles