我正在尝试在Google Chrome中进行扩展,以计算网站上<li>
个元素的数量。问题是我制作的脚本默认情况下不会以ActiveTab DOM为目标,而是以DOM为目标。我怎样才能使它成为ActiveTab DOM的目标而不是Extension DOM?
这是我的manifest.json:
"manifest_version": 2,
"name": "My Extension",
"description": "Still in test",
"version": "1.0",
"background": {
"persistent": false,
"scripts": ["background.js"]
},
"content_scripts": [
{
"matches": ["<all_urls>"],
"js": ["scripts.js"]
}
],
"content_security_policy": "script-src 'self' 'unsafe-eval'; object-src 'self'",
"icons": { "16": "logo.png",
"48": "logo.png",
"128": "logo.png" },
"browser_action": {
"default_icon": "logo.png",
"default_popup": "popup.html",
"default_title": "Click to open menu"
},
"permissions": [
"tabs",
"activeTab",
"https://ajax.googleapis.com/"
]
这是我的按钮:
<input type="button" class="button-1" value="Count elements" id="counter">
这是我在scripts.js中的脚本:
document.addEventListener('DOMContentLoaded', function() {
var link = document.getElementById('counter');
link.addEventListener('click', function() {
console.log(document.getElementById("mylist").getElementsByTagName("li").length);
});
});
这是因为错误的DOM被定位而出现的错误:
Uncaught TypeError: Cannot read property 'getElementsByTagName' of null