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");

解决办法

https://developer.chrome.com/extensions/browserAction#event-onClicked

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) {...};
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() {

解决办法

https://developer.chrome.com/extensions/declarativeContent

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权限

至此问题解决


总结:  遇到这种错误一般都是相关属性使用错误

主要参考官方文档

https://developer.chrome.com/extensions  官方文档首页

https://developer.chrome.com/extensions/samples 官方demo


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值