1. 程式人生 > >background.js Uncaught TypeError: Cannot read property 'xxx' of undefined

background.js Uncaught TypeError: Cannot read property 'xxx' of undefined

chrome extensions 開發過程中 background.js 呼叫chrom.** js的過程中經常遇到

background.js:24 Uncaught TypeError: Cannot read property 'onClicked' of undefined
    at background.js:24

chrome.browserAction.onClicked.addListener(function(tab) {
	alert("hello world");

解決辦法

onClicked

Fired when a browser action icon is clicked.

This event will not fire if the browser action has a popup.

addListener

chrome.browserAction.onClicked.addListener(function callback)
Parameters
function callback

The callback parameter should be a function that looks like this:

function(tabs.Tab tab){...};
提示瞭如果在browser_action 中配置了 popup.html 則單擊事件不起作用
"browser_action": {  
    	"default_icon": "image/icon.png" ,
    	"default_title": "default title",
    	"default_popup": "popup.html" 
  	}, 
去掉default_popup 就可以了


第二個錯誤
_generated_background_page.html:1 Error in event handler for runtime.onInstalled: TypeError: Cannot read property 'onPageChanged' of undefined
    at chrome-extension://ncbflhomeaakikacjdicoamijeabneml/js/background.js:8:27

chrome.runtime.onInstalled.addListener(function() {
	// Replace all rules ...
	chrome.declarativeContent.onPageChanged.removeRules(undefined, function() {

解決辦法

chrome.declarativeContent

Description: Use the chrome.declarativeContent API to take actions depending on the content of a page, without requiring permission to read the page's content. 
Availability: Since Chrome 33. 
Permissions: "declarativeContent" 
查看了一下 declarativeContent的用法, 發現呼叫相關的js方法 需要declarativeContent許可權

至此問題解決

總結:  遇到這種錯誤一般都是相關屬性使用錯誤

主要參考官方文件