使用跨扩展消息API 将消息从扩展 2 发送到扩展 1。如果扩展 1 没有响应,那么您可以提示用户安装扩展 1。我构建了两个 Chrome 扩展来测试这个想法,效果很好。
如果您想下载这些文件并自己尝试,这里是压缩文件。这是一个截屏视频,显示了 YouTube http://youtu.be/6u4tIH6Xfcg上的工作示例
分机 2(从属)
清单.json
{
"name": "Subordinate Chrome Extension Example",
"manifest_version": 2,
"version": "0.1",
"description": "This is an example extension for StackOverflow that requires a master/companion Google Chrome extension to be installed for it to work",
"browser_action": {
"default_popup": "popup.html"
},
"background": {
"scripts": ["background.js"]
}
}
背景.js
chrome.extension.onMessage.addListener(
function(request, sender, sendResponse) {
switch (request.directive) {
case "popup-click":
// check to see if master extension 1 is installed
chrome.extension.sendMessage('jfhngkelgcildagdkgenelgaaaphlghb', {directive: "ping"}, function(extensionResponse) {
if (extensionResponse && extensionResponse.data == 'pong') {
console.log("The master extension 1 is installed!");
} else {
console.log("The master extension 1 is not installed");
}
sendResponse({});
});
return true; // required to return true if we want to sendResponse() later since the cross chrome extension message passing is asynchronus
break;
default:
// helps debug when request directive doesn't match
alert("Unmatched request of '" + request + "' from script to background.js from " + sender);
}
}
);
popup.html
<html>
<head>
<script src="popup.js"></script>
<style type="text/css" media="screen">
body { min-width:250px; text-align: center; }
#click-me { font-size: 20px; }
</style>
</head>
<body>
<button id='click-me'>Click Me!</button>
</body>
</html>
popup.js
function clickHandler(e) {
chrome.extension.sendMessage({directive: "popup-click"}, function(response) {
this.close(); // close the popup when the background finishes processing request
});
}
document.addEventListener('DOMContentLoaded', function () {
document.getElementById('click-me').addEventListener('click', clickHandler);
})
扩展 1(主/同伴)
清单.json
{
"name": "Master Chrome Extension Example",
"manifest_version": 2,
"version": "0.1",
"description": "This is an example extension for StackOverflow that is required for a subordinate/companion Google Chrome extension to work",
"background": {
"scripts": ["background.js"]
}
}
背景.js
chrome.extension.onMessageExternal.addListener(function(request, sender, sendResponse) {
if (sender.id == 'ikofjngppooeeendkfenaiedmlmfjmkb') { // restricting cross extension api to known extension
if (request.directive == 'ping') {
sendResponse({
data: 'pong'
});
}
}
});