Vince
Vince

Reputation: 151

Chrome Extension - onMessage Listener not working

I am trying to execute a script which manipulates the page's html when a chrome extension is clicked. (No popups involed)

The problem is that I can't get the alert("test") working (located in content.js). What am I doing wrong?

Manifest.Json

{
    "name": "test",
    "version": "1.0",
    "manifest_version" :2,
    "description": "test",
    "browser_action" : {
        "default_icon" :"icon.png"
    },
    "background": {
    "scripts": ["background.js"]
    },
      "content_scripts": [ 
  {
  "matches": ["http://*/*","https://*/*"],
  "js": ["content.js"]
  }],
    "permissions": [
    "http://*/*",
    "https://*/*",
    "contextMenus",
    "tabs"
  ]


}

background.js

chrome.browserAction.onClicked.addListener(function(tab) {
       chrome.tabs.sendMessage(tab.id, {
                                     'action': 'SwapNameAndSurname',
                                     'data'  : {'Name' : 'John', 'Surname' : 'Doe'}
                                     });
});

content.js

chrome.runtime.onMessage.addListener(
  function(request, sender, sendResponse) {
   alert("test");
    console.log(sender.tab ?
                "from a content script:" + sender.tab.url :
                "from the extension");
    if (request.greeting == "hello")
      sendResponse({farewell: "goodbye"});
  });

Upvotes: 2

Views: 2054

Answers (1)

mic
mic

Reputation: 4465

I was stuck on this for a while.

Refreshing both the extension and the page did the job.

Upvotes: 1

Related Questions