Chrome.tabs.executeScript does not work in the background

Asked

Viewed 214 times

0

I would like when I click on the extension button to write on the console the title of the page.

My current code is this:

background js.

chrome.browserAction.onClicked.addListener(function() {
    chrome.tabs.executeScript(null, {
        code: 'console.log(document.getElementsByTagName("title")[0].innerText);'
    });
});

manifest.json

{
    "name": "log print",
    "description": "usar console.log()",
    "version": "1",
    "permissions":[
        "tabs",
        "activeTab",
        "https://*/*",
        "http://*/*"
        ],
    "content_security_policy": "script-src 'self' 'unsafe-eval'; object-src 'self'",
    "background": {
        "persistent": true,
        "scripts": ["background.js"]
        },
    "browser_action": {
        "default_title": "Teste",
        "default_popup": "popup.html"
        },
    "manifest_version": 2
}

popup.html

<!DOCTYPE html>
<html>

    <head>
    </head>

    <body>
      <button id="Mr_Button">hello this is a test</button>
    </body>

</html>

1 answer

0


The problem is that if you have a default_popup defined in its manifest file, the event browserAction.onClicked is never called.

The simplest solution would be to take the default_popup.

Another solution would be to call the executeScript by the popup, see how it would look:

popup.html

<script src="popup.js"></script>

popup.js

chrome.tabs.executeScript(null, {
    code: 'console.log(document.getElementsByTagName("title")[0].innerText);'
});

Browser other questions tagged

You are not signed in. Login or sign up in order to post.