从popup.html连接到Chrome扩展中的background.js脚本



在Chrome扩展中从popup.html连接到background.js脚本。当我点击按钮时,我希望后台脚本打开一个新的选项卡

背景脚本:

chrome.runtime.onMessage.addListener(function(message, sender, sendResponse) {    
if (message == "output") {
var win = window.open('https://www.google.ca/webhp?hl=en&sa=X&ved=0ahUKEwjesaKd26TcAhWNw4MKHcN-CwgQPAgD', '_blank');
win.focus();    
}    
});

HTML:

<body>
<script src="next.js"></script> 
<input id="output" type="button" value="Go To Alternative Forum"/>
</body> 

下一篇:

document.getElementById("output").addEventListener(("click"),function(){
chrome.runtime.sendMessage("output"); 
});

您可以通过window.open.来完成此操作

但是,如果你想将你的html连接到background.js,那么官方的方法是将消息从你的脚本next.js发送到background.js,然后background.jss会创建新的选项卡来打开链接。

以下代码将适用于您的情况:

next.js

document.getElementById("next").addEventListener("click",function(){
chrome.runtime.sendMessage({type: "openTab",value:code},function(response) {
});
});

popup.html

<body>
<script src="next.js"></script>
<input id="next" type="button" value="Go to google" />
</body>

background.js

chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
if (request.type == "openTab") {
chrome.tabs.create({"url": "http://www.google.com", "selected": true}, function (tab) {
});
}
});

代码中的脚本引用应该具有src="属性,而不是href="。此处示例:

HTML:

<body>
<script src="next.js"></script>
<input onclick="start();" type="button" value="Go to google" />
</body>

next.js:

function start() {
var win = window.open('https://www.google.ca/webhp?hl=en&sa=X&ved=0ahUKEwjesaKd26TcAhWNw4MKHcN-//CwgQPAgD', '_blank');
win.focus();
}

最新更新