0

I am working on chrome extension and I've stuck on a very specific part where backgroundjs is suppose to send a message to current active tab .

This is my manifest file

manifest.json

{
     "manifest_version": 2,
     "name": "test",
     "description": "Some_Test",
     "version": "1.0",

     "background": {
     "page":  "background.html"
     },
     "content_scripts": [
         {
             "matches": [ "http://*/*", "https://*/*" ],
             "js": [ "content.js" ]
         }
     ],
     "permissions": [
     "background",
     "activeTab",
     "tabs",
     "http://*/*",
     "https://*/*"
     ],
     "browser_action": {
         "default_popup": "popup.html"
      }
}

popup.html

<html>
<body>
    <button id="read-button">Read</button>
    <script type="text/javascript" src="popup.js"></script>
</body>
</html>

popup.js

function readObject(e) {
    console.log(chrome.extension.getBackgroundPage().read());
}

document.getElementById('read-button').addEventListener('click', readObject);

background.html

<!DOCTYPE html>
<html>
    <head>
    </head>
<body>
    <script type="text/javascript" src="background.js"></script>
</body>
</html>

background.js

function read() {
    chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
        chrome.tabs.sendMessage(tabs[0].id, { greeting: "hello" }, function (response) {
            return response.farewell;
        });
    });
}

content.js

chrome.runtime.onMessage.addListener(
  function (request, sender, sendResponse) {
      console.log("hello");
      if (request.greeting == "hello")
          sendResponse({ farewell: "goodbye" });
  });

This is where the error is :

chrome.tabs.sendMessage(tabs[0].id, { greeting: "hello" }, function (response) {
            return response.farewell;
        });

enter image description here

It seems that I cannot access tabs[0] object or I am unable to understand the Array which it returns, because i want to access the active tab and tabs[0] simply means it is getting the first tab in the browser and not the active tab.

1 Answer 1

1

I think this can only happen if the active window is the Developer Tools of the background page.

Just switch to a normal browser window when testing the extension or define read() function in popup.js and remove the background page altogether if it's not absolutely needed.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.