【发布时间】:2014-08-28 14:05:58
【问题描述】:
第一次使用 chrome 扩展 - 我正在制作书签扩展。我希望我的content script 在从网页抓取数据后将数据发送到我的后台弹出页面。
我正在关注official documentation for message passing。所以我有一个内容脚本background.js,代码如下:
var pageInfo = {
'title': document.title,
'url': window.location.href,
'summary': window.getSelection().toString()
};
// Send the information back to the extension
chrome.runtime.sendMessage(pageInfo, function(response){
console.log(response);
});
然后我的后台页面脚本main.js 像这样截取这条消息:
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
$('#title').val(request.title); // this is not working
console.log('request: ', request);
console.log('sender: ', sender);
sendResponse('funky');
}
);
现在数据正在正确地来回传递。上面的那些控制台语句有效!但我的表单字段#title 仍未填充。我的后台页面html(弹出)表单是这样的:
<form id="addbookmark">
<p><label for="title">Title</label><br />
<input type="text" id="title" name="title" size="50" value="" /></p>
<p><label for="url">Url</label><br />
<input type="text" id="url" name="url" size="50" value="" /></p>
<p><label for="summary">Summary</label><br />
<textarea id="summary" name="summary" rows="6" cols="35"></textarea></p>
<p><label for="tags">Tags</label><br />
<input type="text" id="tags" name="tags" size="50" value="" /></p>
<p>
<input id="save" type="submit" value="Save Bookmark" />
<span id="status-display"></span>
</p>
</form>
<script src="jquery.min.js">
</script>
<script src="main.js"></script>
刷新网页时,我的表单字段显示为空
那我做错了什么?我该如何调试和解决这个问题?
这是我的manifest.json 供参考
{
"name": "plugin name",
"version": "0",
"description": "What do I do as an extension",
"background": {
"scripts": ["jquery.min.js", "main.js"]
},
"manifest_version": 2,
"browser_action": {
"name": "Manipulate DOM",
"icons": ["icon.png"],
"default_icon": "icon.png",
"default_popup": "background.html"
},
"permissions": [
"tabs",
"http://*/",
"https://*/"
],
"web_accessible_resources": ["jquery.min.map"],
"content_scripts": [ {
"js": [ "jquery.min.js", "background.js" ],
"matches": [ "http://*/*", "https://*/*"]
}]
}
【问题讨论】:
-
为什么我被否决了?请解释
-
我正在写一个答案,但我投了反对票,因为我发现这个问题没有用。
-
好的。我还在等你的回答...@Xan
-
我用更好的解决方案更新了我的答案。
标签: javascript google-chrome-extension messaging