Yaron Yosef
Yaron Yosef

Reputation: 447

Messaging between chrome extention background,js to content.js

I want to send a message between chrome extension background.js to content.js.

background looks like this:

setInterval(function(){
  chrome.tabs.query({active: true}, function(tabs){
    chrome.tabs.sendMessage(tabs[0].id, {"message": "sample_msg"});
 });
},
1000);

content.js looks like this:

chrome.runtime.onMessage.addListener(function(message, sender) {
  console.log('blablabla');
});

manifest.json looks like this:

{
  "manifest_version": 1,
  "name": "Chrome Extension",
  "description": "",
  "version": "0.0.1",
  "background": {
    "scripts": [
      "/src/background.js"
    ]
  },
  "content_scripts": [
    {
      "matches": [
        "*://google.com/*"
      ],
      "js": [
        "/src/content.js"
      ],
      "all_frames": true
    }
  ],
  "browser_action": {
    "default_popup": "/src/popup.html"
  },
  "permissions": [
    "<all_urls>",
    "activeTab",
    "tabs",
    "cookies",
    "background",
    "contextMenus",
    "unlimitedStorage",
    "storage",
    "notifications",
    "identity",
    "identity.email",
    "webRequest",
    "webRequestBlocking"
  ]
}

I read a lot and I don't get why it is not working? can I have some help? direction? comment?

Upvotes: 0

Views: 62

Answers (1)

Satendra
Satendra

Reputation: 6865

sendMessage API seems correct, But It seems there is a problem with URL match.

Your content scripts will be only injected on google.com domain, As you mentioned in matches key in the manifest file.

Open google.com and check the address bar you can see URL
https://www.google.com/, so to make your content script inject to google domain you need to change your matches

"matches": [
    "https://*.google.com/*"
]

Also, change your onMessage listener as below

chrome.runtime.onMessage.addListener( 
  function(request, sender, sendResponse) {
    console.log("Received message", request.message);
  }
);

Now go to google.com and refresh the page.

Upvotes: 1

Related Questions