【问题标题】:Access DOM from popup.js | Chrome Extension从 popup.js 访问 DOM | Chrome 扩展程序
【发布时间】:2016-09-13 06:48:38
【问题描述】:

我正在尝试制作一个 Chrome 扩展程序,它将获取页面的一些内容(<span> 和 id="productTitile" 的内部 HTML)然后我需要获取该值并将其放入一个字段在我的 popup.html 中。

我试过这个:

document.getElementById('input_87').value = chrome.tabs.executeScript({
    code: 'document.getElementById("productTitle").innerHTML'
});

但它只是将undefined 返回到字段中。然后我在父页面的控制台中运行document.getElementById("productTitle").innerHTML,它给了我预期的值,但是当我在弹出扩展的控制台中运行整个代码时,它再次返回未定义。

我做错了什么?

【问题讨论】:

  • chrome.tabs.executeScript 是一个异步调用,你应该在它的回调中赋值。

标签: javascript html google-chrome google-chrome-extension


【解决方案1】:

首先,正如 Haibara Ai 所说,chrome.tabs.executeScript 是异步的 - 它不返回任何内容(并且不会立即执行任何操作)。

一般来说,一个很好的来源是这个问题:How do I return the response from an asynchronous call? (剧透:你不能)

如果你look at the docs(顺便说一句,这应该是你的第一个无条件反射),你会看到它有一个回调,如果你阅读了上面的问题,你就会明白这是你唯一的选择。但是,还有 2 个额外的并发症:

  1. 回调得到一个数组的结果。发生这种情况是因为executeScript 可以选择(指定allFrames: true 或frameId)在子帧中运行。所以你需要使用结果数组的第一个元素:

    chrome.tabs.executeScript({
      code: 'document.getElementById("productTitle").innerHTML'
    }, function(results) {
      document.getElementById('input_87').value = results[0];
    });
    
  2. 对executeScript 的调用可能会失败 - 例如,无论权限如何,页面都无法编写脚本,例如 Chrome 网上应用店。明智的做法是在使用之前检查您是否确实得到了结果:

    chrome.tabs.executeScript({
      code: 'document.getElementById("productTitle").innerHTML'
    }, function(results) {
      if (chrome.runtime.lastError) {
        // Couldn't execute the script at all
      } else if (typeof results[0] === "undefined") {
        // Couldn't find what we wanted
      } else {
        // Everything is fine
        document.getElementById('input_87').value = results[0];
      }
    });
    

【讨论】:

  • 你好@Xan,如果用户没有指定tabId,executeScript什么时候会在子帧中运行,默认为活动选项卡?
  • 如果用户没有指定allFrames,返回值不会是数组,对吗?
猜你喜欢
  • 2013-03-12
  • 1970-01-01
  • 1970-01-01
  • 2012-01-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多