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

来源:互联网 发布:辽宁省软件协会 编辑:程序博客网 时间:2024/05/17 18:26

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)
Parametersfunctioncallback

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

function( tabs.Tab tab) {...};tabs.Tabtab 
提示了如果在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


0 0
原创粉丝点击