Chrome扩展程序addEventListener为null

问题描述 投票:0回答:1

几周前我刚刚开始学习JS,并且正在尝试构建Chrome扩展程序。我建立了一个manifest.jsonpopup.htmlpopup.jscontent.js文件。

当我尝试在Chrome上运行后台页面控制台以查看popup.js是否正常工作时,我不断收到错误消息:

Uncaught TypeError: Cannot read property 'addEventListener' of null
at popup.js:8

我已经尝试将html中的脚本移动到正文的底部,但它仍然以错误结束并尝试实现:

document.addEventListener('DOMContentLoaded', function () {
    //   My code here.. ( Your code here  )
    }); 

在我的popup.jswindows.onload方法,但仍然无法摆脱错误。

如果有人可以请指出我的代码中的任何错误并告诉我有什么问题我会非常感激。谢谢

POPUP HTML

<!DOCTYPE html>
<html>
<head>
    <title>Like IG Links</title>
</head>

<body>

    <h3><center>Paste Links Below</center></h3>
    <hr>
    <textarea rows="10" cols="60" id="urls"></textarea>
    <br>
    <textarea rows="1" cols="5" id="counter" disabled></textarea>
    <br>
    <br>

    <button type="submit" align="center" style="width:60px;"
            id="start">Start</button>

    <br> 
    <br>

    <button type="submit" align="right" style="width:60px;"
            id="stop">Stop</button>          

   <script type="text/javascript" src="popup.js"></script>              

</body>

</html>

内容JS

console.log('CHROME');

POPUP JS

console.log('background running');

function loadUrls() {
console.log("123");
}

var startbutton = document.getElementById("start");
startbutton.addEventListener('click', loadUrls);    

MANIFEST JSON

{ 
"manifest_version": 2,      
"name": "Like IG Links",
"version": "1.0",    
"description": "Like IG Links",

"content_scripts": [
    {
        "matches": [
            "<all_urls>"
        ],
        "js": ["content.js"]
    }    
],

"background": {
    "scripts": ["popup.js"]
    },

"browser_action": {
"default_icon": "icon.png",  
"default_popup": "popup.html"                 
},

"permissions": ["tabs", "storage", "activeTab"]
}
javascript google-chrome dom google-chrome-extension
1个回答
1
投票

删除清单的后台脚本部分。更新扩展后,错误应该消失。在我正在开发的扩展中,我在HTML和清单中有jquery.js和popup.js。清单的后台脚本标记用于跟踪浏览器事件并持久响应它们的逻辑,而不是扩展HTML后面的js。

© www.soinside.com 2019 - 2024. All rights reserved.