我已阅读文档,这应该是基本的,但我似乎无法显示这些警报。怎么了?
popup.html
<html>
<head>
<script>
function finder() {
chrome.tabs.getSelected(null, function(tab) {
chrome.tabs.sendMessage(tab.id, {type: "feature"}, function(response) {
console.log(response.farewell);
});
});
}
</script>
<style>
p {
border: 1px solid black;
width:200px;
font-size:10px;
}
</style>
</head>
<body>
<p><a id="jira">Click to populate FE description</a></p>
<script>
var jira = document.getElementById('jira');
jira.addEventListener('click', finder, false);
</script>
</body>
</html>
内容脚本:
chrome.extension.onMessage.addListener(function(request, sender, sendResponse) {
alert('sreceived');
if (request.type == "feature") {
alert('score!');
}
});
答案 0 :(得分:5)
Inline JavaScript will not be executed. This restriction bans both inline blocks and inline event handlers(例如<button onclick="...">
)。
通过上面的行很明显,你的popup.html违反了限制,可以通过以下方式解决:
删除<script>
中的所有popup.html
代码,并将原始代码移至popup.js
。
<html>
<head>
<script src="popup.js"></script> <!-- Added this line -->
<style>
p {
border: 1px solid black;
width:200px;
font-size:10px;
}
</style>
</head>
<body>
<p><a id="jira">Click to populate FE description</a></p>
</body>
</html>
我没有在popup.js
中复制粘贴代码。这些是我所做的改变:
chrome.tabs.getSelected()
支持chrome.tabs.query()
,因此我更新了chrome.tabs.getSelected(null, function(tab) {});
console.log(response.farewell);
,因为内容脚本没有响应处理程序。最终的popup.js
function finder() {
chrome.tabs.query({
"status": "complete",
"currentWindow": true,
"active": true
}, function (tabs) {
chrome.tabs.sendMessage(tabs[0].id, {
type: "feature"
}, function (response) {
//console.log(response.farewell);
});
});
}
document.addEventListener('DOMContentLoaded',= function() {
document.getElementById('jira').onclick = finder;
});
manifest.json的注意事项
"permissions":["tabs","<all_urls>"],
内容脚本的权限
"content_scripts": [
{
"matches": ["<all_urls>"],
"js": ["content.js"]
}
]
最终manifest.json
{
"name":"Basic Message Passing",
"description":"This demonstrates Basic Message Passing",
"browser_action":{
"default_popup":"popup.html",
"default_icon":"screen.png"
},
"manifest_version":2,
"version":"2",
"permissions":["tabs","<all_urls>"],
"content_scripts": [
{
"matches": ["<all_urls>"],
"js": ["content.js"]
}
]
}
您的内容脚本很好,所以我没有更改它。
<强>输出:强>
如果您需要更多信息,请与我们联系。