【问题标题】:Uncaught TypeError: Cannot read property 'colors' of undefined未捕获的类型错误:无法读取未定义的属性“颜色”
【发布时间】:2017-05-20 02:03:56
【问题描述】:

我正在尝试创建一个 chrome 扩展,允许用户在单击扩展按钮时向图形计算器 Desmos 添加新颜色。

两个基本文件:

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

(function() {

  if (window.location.href === "https://www.desmos.com/calculator") {

    var name = prompt("What would you like the name of the new color to be?");
    var hex = prompt("What should the hex code of the new color be?");

    window.Calc.colors[name] = hex;

  };

})();

但是当我尝试运行它时,我得到了Uncaught TypeError: Cannot read property 'colors' of undefined。如果我使用 DevTools 控制台运行它,它会完美运行。有人能解释一下原因吗?

【问题讨论】:

标签: javascript typeerror


【解决方案1】:

您无法从内容脚本访问网页的已评估 Javascript 变量。您的扩展脚本、内容脚本和页面脚本在不同的上下文中运行。您的内容脚本可以访问页面的 DOM 而不是执行上下文。因此,您需要您的内容脚本通过添加脚本标签直接将代码注入页面的 DOM。

总结。

  • 扩展脚本可以访问 chrome 选项卡。
  • 内容脚本可以访问页面 DOM。
  • 页面脚本在与其他脚本不同的上下文中执行。
  • 内容脚本必须通过添加脚本标签来注入代码。
  • 注入的代码可以访问页面的评估 javascript 变量。
  • 注入的代码可以使用window.postMessage 与内容脚本通信
  • 然后内容脚本可以通过chrome API 与扩展脚本通信。

不好玩……

【讨论】:

    猜你喜欢
    • 2021-12-19
    • 2021-12-22
    • 2015-01-06
    • 2017-07-26
    • 2019-02-26
    • 2021-12-25
    • 2019-01-05
    相关资源
    最近更新 更多