Pergunta

I am practising google chrome extension development. I was trying to send message from my popup.js to content.js file and I am getting the following error:

"Uncaught ReferenceError: tabs is not defined"

This error comes in my popup.js file.

Following are my code files

manifst.json

{
"manifest_version": 2,

"name": "by-Surfers",
"description": "This extension is for practice...",
"version": "0.0.1",
"browser_action": {
    "default_icon": "icon.png",
    "default_title": "Click to speak with other surfers..",
    "default_popup": "popup.html"
},
"background": {
    "scripts": ["event.js"],
    "persistent": false
},
"permissions": [
      "tabs"
    ],
"content_scripts": [
    {
        "matches": ["http://*/*", "https://*/*"],
        "js": ["content.js"]
    }
]

}

Popup.html

<!DOCTYPE html>
<html>
<head>
<script src="jquery-2.1.1.min.js"></script>
<script src="popup.js"></script>
<style>
      body {
        min-width: 300px;
        overflow-x: hidden;
      }
    </style>
</head>
<body>
It will start now....
<button id='btn'>click me</button>
</body>
</html>

popup.js

$(document).ready(function(){
    $('#btn').click(function(){
        StartTab();
    });
});

function StartTab(){
        chrome.tabs.sendMessage(tabs[0].id, {greeting: "OpenDialog"}, function(response) {
                // console.log(response.farewell);
            });
    }

event.js

chrome.browserAction.setBadgeText({text: "CET"});

chrome.extension.onMessage.addListener(function(request, sender, sendResponse) {
    switch(request.type) {
        case "dom-loaded":
            alert(request.data.myProperty);
        break;
    }
    return true;
});

function OpenContentScript(){

}

content.js

chrome.runtime.onMessage.addListener(
    function(request, sender, sendResponse) {
        console.log(sender.tab ?
                "from a content script:" + sender.tab.url :
                "from the extension");

        if (request.greeting == "OpenDialog"){
            RunIt();
        }
});

function Runit(){
    alert("it has started...");
}

Please help!!!

Foi útil?

Solução

The problem is tabs[0].id, as tabs is not defined anywhere.

If you're trying to send to the currently active tab, you can try this:

function StartTab(){
    chrome.tabs.query({active: true, currentWindow: true}, function(tabs){
        chrome.tabs.sendMessage(
            tabs[0].id,
            {greeting: "OpenDialog"},
            function(response) {
                // console.log(response.farewell);
            }
        );
    });
}

I suppose you actually copied this code from a similar example and forgot the query wrapper.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top