【问题标题】:Google Chrome: can't getElementById from chrome extension谷歌浏览器:无法从 chrome 扩展中获取ElementById
【发布时间】:2020-02-22 19:48:11
【问题描述】:

例如,我正在尝试在https://developer.chrome.com/extensions/browserAction 读取 id="tooltip" 元素的文本

以下代码在控制台中可以正常工作:

var element = document.getElementById('tooltip');
if(element != null) {alert(element.innerText);}
else {alert("element contains null");}

来自扩展的相同代码 run 显示“元素包含 null”。

chrome.browserAction.onClicked.addListener
(
  function(tab)
  {
    var element = document.getElementById('tooltip');
    if(element != null) {alert(element.innerText);}
    else {alert("element contains null");}
  }
);

这并不奇怪,因为 document 对象包含 _generated_background_page.html,而不是我的相关页面。我需要的实际页面似乎包含在 tab 对象中。那么现在的问题是如何在tab中搜索“tooltip”?

我用下面的代码查看了上述对象的内容: alert(JSON.stringify(tab, null, 4));
alert(JSON.stringify(document, null, 4));

【问题讨论】:

  • 我想知道alert(element); 显示了什么。也许这段代码不在实际页面中运行,并且正在找到其他一些元素。
  • 感谢 user212514,这是一个很好的猜测。原来 element 包含null.
  • 还发现 document 包含 _generated_background_page.html,而不是我的页面。我需要的实际页面包含在 tab 对象中。所以现在的问题是如何在tab中搜索?tab.getElementById(...)返回错误。

标签: javascript google-chrome innertext


【解决方案1】:

我似乎找到了解决办法。我不确定它是否是最优雅的,但它仍然有效。

我创建了第二个名为 script2.js 的脚本,并从 script1.js 中引用它。

下面是 script1.js 的内容,当我点击浏览器工具栏中的扩展按钮时执行:

chrome.browserAction.onClicked.addListener(function(tab){
  chrome.tabs.executeScript(null, {file: "script2.js"});
});

script1.js 调用 script2.js 包含主要代码:

var element = document.getElementById('tooltip');
if(element != null) alert(element.innerText);
else alert('element is null');

【讨论】:

    【解决方案2】:

    也许是onclick而不是onclicked

    chrome.browserAction.onClick.addListener
    (
      function(tab)
      {
        var element = document.getElementById('tooltip');
        alert(element.innerText);
      }
    );
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-01-25
    • 2011-10-15
    • 2015-04-17
    • 2014-07-24
    • 1970-01-01
    相关资源
    最近更新 更多