use*_*676 11 google-chrome-extension
我想通过浏览器操作按钮打开它时更新popup.html中的html.popup.js应该向当前选项卡上运行的内容脚本发送消息,并且应该收到响应并更新html.但是,内容脚本不会收到任何消息,因此不会发送正确的响应.
Content.js
var text = "hello";
chrome.runtime.onMessage.addListener(
function(message, sender, sendResponse) {
switch(message.type) {
case "getText":
sendResponse(text);
break;
}
}
);
Run Code Online (Sandbox Code Playgroud)
Popup.js
chrome.tabs.getCurrent(function(tab){
chrome.tabs.sendMessage(tab.id, {type:"getText"}, function(response){
alert(response)
$("#text").text(response);
});
});
Run Code Online (Sandbox Code Playgroud)
的manifest.json
{
"manifest_version": 2,
"name": "It's Just A Name",
"description": "This extension is able to",
"version": "1.0",
"permissions" : ["tabs"],
"browser_action": {
"default_icon": "icon.png",
"default_popup": "popup.html",
"default_title": "Click here!"
},
"content_scripts": [
{
"matches": ["https://*/*"],
"js": ["jquery.min.js","content.js"]
}]
}
Run Code Online (Sandbox Code Playgroud)
Popup.html
<!doctype html>
<html>
<head>
<title>Title</title>
<style>
body {
font-family: "Segoe UI", "Lucida Grande", Tahoma, sans-serif;
font-size: 100%;
}
#status {
white-space: pre;
text-overflow: ellipsis;
overflow: hidden;
max-width: 400px;
}
</style>
<script src="popup.js"></script>
</head>
<body>
<p id="text"></p>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
Del*_*iaz 11
chrome.tabs.getCurrent用于:
获取此脚本调用的选项卡
你的popup.js应该是:
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
chrome.tabs.sendMessage(tabs[0].id, {type:"getText"}, function(response){
alert(response)
$("#text").text(response);
});
});
Run Code Online (Sandbox Code Playgroud)
要添加到上述答案,您通常希望从弹出窗口向所有选项卡发送消息,因此
弹出:
chrome.tabs.query({}, tabs => {
tabs.forEach(tab => {
chrome.tabs.sendMessage(tab.id, msgObj);
});
});
Run Code Online (Sandbox Code Playgroud)
内容脚本:
chrome.runtime.onMessage.addListener(msgObj => {
// do something with msgObj
});
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
7402 次 |
最近记录: |