0

this is a bit of my code that I have currently

Manifest

{
  "name": "hidden",
  "manifest_version": 2,
  "content_security_policy": "script-src 'self'; object-src 'self'",
  "permissions": [
    "activeTab",
    "storage"
  ],
  "version": "hidden",
  "icons": {hidden},
  "description": "hidden",
  "browser_action": {hidden},
  "content_scripts": [
    {
      "matches": [hidden],
      "run_at": "document_start",
      "js": [ "injected.js", "content.js"]
    }
  ],
  "web_accessible_resources": ["injected.js"],
  "background": {
    "scripts": ["background.js"],
    "persistent": false
  }
}

Injected.js

if (new RegExp(allowedUrls.join("|")).test(this._url)) 
{
    console.log('test') <- I can see this message in console
    chrome.runtime.sendMessage({interception: true});
}

Background.js

console.log("Atleast reached background.js") <- I can see that
chrome.runtime.onMessage.addListener(function (message, sender) {
console.log('inside listener') <- I cannot see that which means it doesn't get fired on message sent
    if (message.interception) {
        chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
            chrome.tabs.sendMessage(tabs[0].id, {interception: true});
        });
    }
});

Can someone help me and tell me why it isn't working? My goal is to intercept XHR request in one file (injected.js), then receive that message on background.js and send that to another content.js file and do some stuff base on the response.

  • The posted fragments are fine so apparently the problem is caused by something else. Might be helpful to show us your manifest.json. Also make sure you don't load the background script anywhere explicitly, it should be simply declared in `background` section of manifest.json. BTW you can simplify your messaging by using a callback as shown in [this topic](https://stackoverflow.com/a/20695181). – wOxxOm Mar 14 '21 at 17:43
  • I have edited the post and added manifest. –  Mar 14 '21 at 17:46
  • Judging by `web_accessible_resources` you probably run injected.js as a page script in which case it can't use chrome.runtime.sendMessage by default. You'll need to use a different listener and make changes to manifest.json, see [the documentation](https://developer.chrome.com/extensions/messaging#external-webpage). – wOxxOm Mar 14 '21 at 17:49
  • THANKS. Works like a charm! –  Mar 14 '21 at 18:02

0 Answers0