chrome.tabs.executeScript does not work in background

0

I would like, when I clicked the extension button, I wrote in 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>
    
asked by anonymous 02.09.2018 / 10:00

1 answer

0

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

The simplest solution would be to get default_popup .

Another solution would be to call executeScript through 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);'
});
    
02.09.2018 / 14:27