我已开始实施Chrome扩展程序,旨在向用户显示来自RSS Feed的链接。
浏览器操作扩展包含一个后台脚本(bg.js)和一个带有jQuery和popup.js的popup.html
据我所知,一切正常,直到应该在bg.js中调用callback()
并在popup.js中收到。似乎永远不会触发popup.js中的回调。
我检查了后台页面控制台和弹出控制台......没有错误。
为了从bg.js收到repsonse,我需要更改什么?
顺便说一句:使用chrome.runtime.sendMessage
和chrome.extension.sendMessage
之间的区别是什么?
manifest.json看起来像
{
"manifest_version": 2,
"name": "heise Newsticker",
"description": "Der RSS-Feed des heise Newstickers.",
"version": "1.0",
"icons": {
"128" : "logo128.png"
},
"background": {
"persistent": true,
"scripts": ["bg.js"]
},
"permissions": [
"http://www.heise.de/newsticker*",
"http://heise.de.feedsportal.com/c/35207/f/653902/index.rss"
],
"browser_action": {
"default_icon": "logo.png",
"default_popup": "popup.html"
}
}
这是bg.js
function fetch_feed(url, callback) {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(data) {
if (xhr.readyState == 4) {
if (xhr.status == 200 || xhr.status == 304) {
console.log("Request successful");
var data = xhr.responseText;
callback(data);
} else {
console.log("Request not successful");
callback(null);
}
}
}
// Note that any URL fetched here must be matched by a permission in
// the manifest.json file!
xhr.open('GET', url, true);
xhr.send();
}
function onMessage(request, sender, callback) {
console.log("onmessage received with URL: " + request.url);
if (request.action == 'fetch_feed') {
fetch_feed(request.url, callback);
}
}
console.log('listener installed');
// Wire up the listener.
chrome.extension.onMessage.addListener(onMessage);
popup.html
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="popup.js"></script>
</head>
<body>
<div id="ziel"></div>
</body>
</html>
最后:popup.js
$(document).ready(function() {
fetch_feed();
});
function fetch_feed() {
console.log("starting");
chrome.extension.sendMessage({'action' : 'fetch_feed', 'url' : 'http://www.heise.de/newsticker/heise-atom.xml'},
function(response) {
console.log("Response successfully received: " + response);
display_stories(response);
}
);
}
function display_stories(xml) {
$('#ziel').html("<h3>now displaying</h3>");
}
答案 0 :(得分:0)
解决方法(和简化):我从bg.js中删除了所有内容,并将XMLHttpRequest移到了popup.js
所以没有更多的消息传递...这解决了我的问题,但问题仍然有点奇怪