我是Chrome扩展编码的新手,而且是javascript的新手。扩展名为 page_action 类型。我正在尝试通过点击popup.html中的按钮向background.js发送一条简单的消息。我在这个网站上看到了类似的问题,但似乎没有任何效果。加载扩展是好的。请帮忙
/* __background.js__ */
function checkForValidUrl(tabId, changeInfo,tab){
console.log("Extension loaded");
chrome.pageAction.show(tabId);
}
function readMessage (request, sender, sendResponse){
alert("reached");
console.log(request.greeting);
sendRequest({farewell:"goodbye"});
}
chrome.extension.onRequest.addListener(readMessage);
chrome.tabs.onUpdated.addListener(checkForValidUrl);
/* __manifest.json__ */
{
"name": "DemoExtension",
"version": "1.0",
"manifest_version": 2,
"background": {
"scripts": [
"jquery.js",
"background.js"
]
},
"description": "demo extension to learn coding chrome extensions.",
"icons": {
"16": "images/16x16.png",
"48": "images/48x48.png",
"128": "images/128x128.png"
},
"page_action": {
"default_icon": {
"19": "images/19x19.png",
"38": "images/38x38.png"
},
"default_title": "Demo extension",
"default_popup": "popup.html"
},
"options_page": "options.html",
"permissions": [
"tabs",
"storage",
"http://*/*",
"https://*/*"
]
}
-
__popup.html__
<!DOCTYPE HTML>
<html>
<head>
<title>Demo extension</title>
<script src="./popup.js"></script>
</head>
<body>
<button id="clickMe">Add</button>
</body>
</html>
-
__popup.js__
function sendMessageToExtn() {
alert("reached in popup");
chrome.extension.sendMessage({
greeting : "hello" },
function(response) { console.log(response.farewell);
});
}
document.getElementById('clickMe').addEventListener('click', function () {
sendMessageToExtn();
});
我现在收到错误未捕获TypeError:无法调用null(匿名函数)的方法'addEventListener'
有类似的question。
答案 0 :(得分:0)
解决了这个问题。首先纳入@apsillers的建议。然后最后移动
`<script src="./popup.js"></script>
从头部开始,在按钮标签下方。