N_X41
N_X41

Reputation: 13

sendMessage not working in chrome extension

I am trying to make a simple chrome extension. I'd be glad if someone can help.

Objective: When you click the button in extension popup (popup.html), the title of current webpage is displayed in div (with id 'div1').

Problem: I have searched internet for doing this and found that passing message can be used to achieve the same. So I tried my hands on it. But its not working. I want to know what went wrong.

Status:

= The extension is successfully imported in chrome.

= when extension icon is clicked, it shows proper popup.

= when button is clicked nothing happens.

= developer console shows no error.

Files:

=====================================

 //manifest.json
    {
      "manifest_version": 2,
      "name": "some_name_extension",
      "version": "0.0.1",
      "content_scripts": [
        {
          "matches": [
          "<all_urls>"
          ],
          "js": ["jquery-3.2.1.js", "content_script.js"]
        }
      ],
      "browser_action": {
        "default_icon": "icon.png",
        "default_popup": "popup.html"
       }
    }

=====================================

<!-- popup.html -->
<! doctype html>
<html>
<head>
    <title>
    </title>
    <script type="text/javascript" src="popup.js">
    </script>
    <style>
        html
        {
            height: 200;
            width: 200;
        }
    </style>
</head>
<body>
    <button id="btn1">
        click me!
    </button>
    <div id="div1">
        (title will be displayed here)
    </div>
</body>
</html>

=====================================

//content_script.js
document.addEventListener('DOMContentLoaded', function() {
var title1=document.getElementsByTagName("title")[0].innerHTML;

chrome.extension.onMessage.addListener(

function(msg, sender, sendResponse) {
    if(sender=="popup")
    {
        chrome.extension.sendMessage(title1,"content","1");
    }
   });
 });

=====================================

//popup.js
document.addEventListener('DOMContentLoaded', function() {
    var mainBtn = document.getElementById('btn1');
    mainBtn.addEventListener('click', function() {
        chrome.extension.sendMessage("button_clicked","popup","1");
    });

    chrome.extension.onMessage.addListener(

    function(msg, sender, sendResponse) {
        if(sender=="content")
        {
            document.getElementById("div1").innerHTML=msg;
        }
    } 
   );
 });

=====================================

link to jquery script file : https://code.jquery.com/jquery-3.2.1.js

Upvotes: 1

Views: 1386

Answers (1)

woxxom
woxxom

Reputation: 73556

  1. sender is an object that's set by the browser automatically, not a string that you can pass yourself. Use the devtools debugger to inspect your code and variables by setting breakpoints inside the callbacks, don't write the code blindly.
  2. There's no need to check the sender in this case because content scripts cannot message each other anyway.
  3. The correct method of sending a message to a content script from the popup is chrome.tabs.sendMessage with tabId as the first parameter:

    chrome.tabs.query({active: true, currentWindow: true}, ([tab]) => {
      chrome.tabs.sendMessage(tab.id, {
        action: 'setTitle', 
        title: title1,
      });
    });
    
  4. To send many values at once use an object: {action: 'setTitle', title: title1} or {action: 'buttonClicked', data: 1} and so on.

  5. chrome.extension is deprecated for messaging, use chrome.runtime
  6. Your code doesn't use jQuery so there's no need to inject it in manifest.json

Upvotes: 0

Related Questions