user1214678
user1214678

Reputation:

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 content script once I reload the extension and change to the tab quickly.. 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 alert box only triggers after reloading the extension and quickly switch to the tab where the alert box is supposed to show up.

So I thought background.js was supposed to load every time I reload the tab. But right now it's only loading once, and if I am not at that tab it loads before helper.js is ready to send a response. That's my theory. But as I said, I'm new to this, and I'm struggling to understand how it works.

Ultimately what I'm trying to accomplish is having the user save some options that will load by default every time the page loads. Saving the options in the options page is working just fine. The popup page is also working as it should. I just can't get the default options to load, because I can't get the message to the content script page.

Upvotes: 4

Views: 5562

Answers (1)

BeardFist
BeardFist

Reputation: 8201

The background page will run every time the extension is loaded, and since it is an event page, it will unload and any event to it will execute your code again. Try doing 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"});
});

This way the content script starts the flow of information so you know for sure that it is ready to receive it.

Upvotes: 7

Related Questions