Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/windows/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript Chrome扩展:未捕获引用错误:未定义函数_Javascript_Google Chrome Extension - Fatal编程技术网

Javascript Chrome扩展:未捕获引用错误:未定义函数

Javascript Chrome扩展:未捕获引用错误:未定义函数,javascript,google-chrome-extension,Javascript,Google Chrome Extension,我正在写一个Chrome扩展,我有这个页面: <html> <body> <button id="changeColor"></button> <script src="popup.js"></script> </body> </html> 为什么?问题:外部函数的代码没有被注入。 以下是executeScript的功能: 它将函数的

我正在写一个Chrome扩展,我有这个页面:

<html>
  <body>
    <button id="changeColor"></button>
    <script src="popup.js"></script>
  </body>
</html>

为什么?

问题:外部函数的代码没有被注入。

以下是executeScript的功能:

  • 它将函数的代码作为纯文本IIFE,即
    (function foo(){…})(
  • 它将文本传输到网页
  • 它选择“隔离世界”环境,在该环境中运行扩展的所有内容脚本
  • 它以JavaScript代码的形式执行该文本
解决方案:将所有必要的代码和函数放入您注入的函数中。

在您的情况下,getElementByXpath定义应该移动到setPageBackgroundColor中


当然,注入的代码也可以通过manifest.json的
content\u脚本
(假设它们已经发生)或
executeScript
使用先前注入内容脚本的全局变量/函数问题:外部函数的代码没有被注入。

以下是executeScript的功能:

  • 它将函数的代码作为纯文本IIFE,即
    (function foo(){…})(
  • 它将文本传输到网页
  • 它选择“隔离世界”环境,在该环境中运行扩展的所有内容脚本
  • 它以JavaScript代码的形式执行该文本
解决方案:将所有必要的代码和函数放入您注入的函数中。

在您的情况下,getElementByXpath定义应该移动到setPageBackgroundColor中

当然,注入的代码也可以通过manifest.json的
content\u脚本
(假设它们已经发生)或
executeScript
,使用先前注入内容脚本的全局变量/函数

let changeColor = document.getElementById("changeColor");

chrome.storage.sync.get("color", ({ color }) => {
  changeColor.style.backgroundColor = color;
});

changeColor.addEventListener("click", async () => {
    let [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
  
    chrome.scripting.executeScript({
      target: { tabId: tab.id },
      function: setPageBackgroundColor,
    });

});
  
function setPageBackgroundColor() {
  chrome.storage.sync.get("color", ({ color }) => {
    document.body.style.backgroundColor = color;
  });
  // Here, it says: Uncaught ReferenceError: getElementByXpath is not defined
  console.log(getElementByXpath("xpath").textContent);
}
  
function getElementByXpath(path) {
  return document.evaluate(path, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
}