本文介绍了chrome.tabs.executeScript没有从内容页面返回结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个chrome扩展程序,尝试从我所在的网页返回所有h2标签.如果chrome.tabs.executeScript很简单,例如

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")'
});

但以下操作无效

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:

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);
    }
});

除了名称,描述,版本.这是我的manifest.js

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://*/*"
]

我正在测试的代码来自此处的答案之一. chrome.tabs.executeScript():如何获得结果内容脚本?

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

它可能相关,也可能不相关,但是当我将警报消息放入回调函数中时,它们会立即消失.我试过包括所有allFrames:细节上为true,但没有运气.

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.

推荐答案

您不能使用executeScript返回DOM节点.但是,如果您需要他们的innerHTML,则可以使用它返回一个数组.

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);
});

这篇关于chrome.tabs.executeScript没有从内容页面返回结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-10 00:31