Chrome扩展程序中未捕获的TypeError

时间:2018-03-23 18:37:22

标签: javascript html google-chrome-extension

我的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);

1 个答案:

答案 0 :(得分:0)

options.js中添加

  let page = document.getElementById('buttonDiv');

您从教程网站下载的文件不是最新的

使用教程中的代码片段,而不是下载的文件。