未捕获的引用错误:即使在加载 JS 后,在 chrome 扩展名中也没有定义 HTMLInspector

Uncaught ReferenceError: HTMLInspector is not defined, even after JS is loaded, in chrome extension

本文关键字:扩展名 chrome HTMLInspector 定义 加载 引用 错误 JS      更新时间:2023-09-26

我想创建一个chrome扩展程序,以便在网页上运行HTML验证器。

chrome.browserAction.onClicked.addListener(function(tab){
   chrome.tabs.executeScript(tab.id, {file: "inject.js"}, function(){
    alert(results);
});});

下面 id 中的代码inject.js

var js = document.createElement("script");
js.type = "text/javascript";
js.src = "https://cdnjs.cloudflare.com/ajax/libs/html-inspector/0.8.1/html-inspector.js";
document.body.appendChild(js);
HTMLInspector.inspect();

在 DOM 上,我看到脚本标签被添加到body标签上方。但是HTMLInspector.inspect();的行会引发错误。我该怎么做才能解决这个问题?

如果你使用的是jquery,请尝试这样做:将其添加到head。

<script>
 var js = document.createElement("script");
 js.type = "text/javascript";
 js.src = "https://cdnjs.cloudflare.com/ajax/libs/html-inspector/0.8.1/html-inspector.js";
 $("head").append(js)
 window.onload = function() {
 HTMLInspector.inspect();
 }
</script>