扩展主要由3部分组成。
- popup
- content_scripts
- background
消息传递,一般指3部分之间发送接收消息。
消息的监听机制
监听消息都是一样的。
chrome.extension.onMessage.addListener(
function(request, sender, sendResponse) {
console.log('收到消息',request);
sendResponse("回答处理结果");
}
);
他们是怎么相互通信的?
-
popup
发送消息到background
chrome.runtime.sendMessage({from: "popup"},
function(response) {
console.log(response);
}
);
image.png
-
background
发送消息到popup
chrome.runtime.sendMessage({greeting: "dd"},
function(response) {
console.log(response);
}
);
-
content_scripts
发送消息到background
chrome.runtime.sendMessage({from: "content_scripts"}, function(response) {
console.log(response);
});
-
content_scripts
发送消息到popup
chrome.runtime.sendMessage({from: "content_scripts"}, function(response) {
console.log(response);
});
-
popup
发送消息到content_scripts
chrome.tabs.query({active: true, currentWindow: true}, function(tabs)
{
chrome.tabs.sendMessage(tabs[0].id, {from:'popup',to:'content_scripts'}, function(response)
{
console.log(response);
});
});
-
background
发送消息到content_scripts
chrome.tabs.query({active: true, currentWindow: true}, function(tabs)
{
chrome.tabs.sendMessage(tabs[0].id, {from:'background',to:'content_scripts'}, function(response)
{
console.log(response);
});
});
注意事项
-
content_scripts
发送消息popup
和background
都可以收到
网友评论