Millicent
Millicent

Reputation: 86

chrome.tabs.executeScript is not returning results from content page

I am working on a chrome extension where I attempt to return all h2 tags from the web page i am on. chrome.tabs.executeScript will work if its simple such as

chrome.tabs.executeScript(null,{
    code: 'console.log("hello")'
});

but the following will not work

chrome.tabs.executeScript(null,{
    code: 'document.getElementsByTagName("h2");'
},function (results){
    alert(results.length);
    for(var i = 0; i < results.length;i++){
        console.log(results[i].innerHTML);
    }
});

index.html:

<body>
<h1>app</h1>
<div id="container">
  <span>Choose an action</span>
  <button id="someFunc">click here for function</button>
  <script type="text/javascript" src="popup.js"></script>
</div>

popup.js

chrome.tabs.executeScript(null,{
    code: 'document.getElementsByTagName("h2");'
},function (results){
    alert(results.length);
    for(var i = 0; i < results.length;i++){
        console.log(results[i].innerHTML);
    }
});

other than the name, description, version. this is my manifest.js

"browser_action": {
"default_icon": "icon.png",
"default_popup": "popup.html"
},

"permissions": [
"activeTab",
"storage","http://*/*",
"https://*/*"
]

The code I'm testing is from one of the answers here. chrome.tabs.executeScript(): How to get result of content script?

It may or may not be relevant but when I put alert messages in the callback function they disappear instantly. I've tried including all allFrames: true in the details but no luck.

Upvotes: 1

Views: 1809

Answers (1)

Denis L
Denis L

Reputation: 3292

You can't return DOM nodes using executeScript. But if you need their innerHTML you can return an array with it.

chrome.tabs.executeScript(null,{
    code: 'Array.from(document.getElementsByTagName("h2")).map(h => h.innerHTML)'
},function (results){
    console.log(results);
});

Upvotes: 1

Related Questions