Search code examples
google-chromegoogle-chrome-extensionmessagingcontent-script

Chrome Extension - Event Pages/Message Passing is not working


I'm novice in Google Chrome Extension development and I'm running through an issue which is causing the content script not getting executed. Below is a detailed description of the issue.

I'm working an extension to read some DOM content from a web site per say example.com I've the following files and the respective code part of it.

manifest

{
    "manifest_version" : 2,

    "name" : "My First Chrome App",
    "description" : "My First Chrome App",
    "version": "1.0",

    "browser_action" : {
        "default_title" : "Hello"
    },

    "permissions" : ["tabs"],

    "background" : {
        "scripts" : ["background.js"],
        "persistence" : false
    },

    "content_scripts":[
    {
      "matches": [
        "http://example.com/HomePage.aspx"
      ],
      "js": ["jquery_224.js", "content_script.js"]
    }]
}

background.js

My intention is to create a tab and surf to a page which is mentioned in the below script. And, it has to send a message to content_script.js

chrome.browserAction.onClicked.addListener(function(){
  chrome.tabs.create({ url: "http://example.com/HomePage.aspx" }, function(tab){
    chrome.runtime.sendMessage({authKey : "parse-dom"});
    setTimeout(function(){
        chrome.tabs.remove(tab.id);
    }, 2000);
  });
});.

content_script.js

Here I'm trying to read the authKey that I'm sending it from my background.js

chrome.runtime.onMessage.addListener(function(request,sender,response){
    alert(request.authKey);
});

Unfortunately, I'm not getting the alert nor seeing any script errors. I have gone through the Chrome Messaging API and followed the same

Where am I going wrong?


Solution

  • Try with

    "content_scripts":[
    {
        "run_at": "document_start",
    

    More infos: https://developer.chrome.com/extensions/content_scripts

    or try putting a timeout on your background sendMessage

    EDIT: I've also noticed on manifest.json you have an HTTPS match while you are creating a tab with an HTTP address