我的Chrome扩展程序中出现以下错误:
Uncaught TypeError: Cannot read property 'id' of undefined at HTMLButtonElement.changeColor.onclick (color.js:10)
我有background.js
:
chrome.runtime.onInstalled.addListener(function() {
chrome.storage.sync.set({
color: '#3aa757'
}, function() {
console.log("The color is green.");
});
chrome.declarativeContent.onPageChanged.removeRules(undefined, function() {
chrome.declarativeContent.onPageChanged.addRules([{
conditions: [new chrome.declarativeContent.PageStateMatcher({
pageUrl: {
hostEquals: 'www.amazon.in'
},
})],
actions: [new chrome.declarativeContent.ShowPageAction()]
}]);
});
});
和color.js
文件:
let changeColor = document.getElementById('changeColor');
tabs = new Array();
chrome.storage.sync.get('color', function(data) {
changeColor.style.backgroundColor = data.color;
changeColor.setAttribute('value', data.color);
});
window.onload = function() {
changeColor.onclick = function(element) {
let color = element.target.value;
chrome.tabs.executeScript(
tabs[0].id, {
code: 'document.body.style.backgroundColor = "' + color + '";'
});
}
};
index.html
档案:
<button id="changeColor"></button>
<script src="color.js"></script>
options.html
档案:
<script src="options.js"></script>
options.js
档案:
const kButtonColors = ['#3aa757', '#e8453c', '#f9bb2d', '#4688f1']
function constructOptions(kButtonColors) {
for (let item of kButtonColors) {
let button = document.createElement('button');
button.style.backgroundColor = item;
button.addEventListener('click', function() {
chrome.storage.sync.set({
color: item
}, function() {
console.log('color is ' + item);
})
});
page.appendChild(button);
}
}
constructOptions(kButtonColors);
答案 0 :(得分:0)
在options.js
中添加
let page = document.getElementById('buttonDiv');
您从教程网站下载的文件不是最新的
使用教程中的代码片段,而不是下载的文件。