我正在使用Chrome扩展程序,在用户在弹出窗口中输入时间后关闭当前正在运行的选项卡。弹出窗口包含几个按钮,用于选择计时器的时间。
我的问题是,当我在该标签上处于活动状态时,它没有关闭标签。
如果在设置时间并开始等待后我没有在该选项卡上执行任何操作,那么它可以正常工作,但我不希望出现这种情况。我想在用户在该选项卡上执行某些操作时关闭选项卡。我怎么能做到这一点?
的manifest.json
{
"manifest_version": 2,
"name": "Tab Close",
"version": "0.1",
"content_scripts": [
{
"matches": [
"<all_urls>"
],
"js": ["content.js"]
}
],
"background": {
"scripts": ["background.js"]
},
"permissions" : ["tabs", "active"],
"browser_action": {
"default_icon": "time.png",
"default_popup": "index.html",
"default_title": "Set time!"
}
}
content.js
chrome.runtime.sendMessage({type : "close tab"});
background.js
console.log('running....');
chrome.runtime.onMessage.addListener(receiver);
window.tab_id = "";
function receiver(request, sender, sendResponse) {
if (request.type == "close tab") {
console.log(sender.tab.id);
window.tab_id = sender.tab.id;
}
}
的index.html
<!DOCTYPE>
<html>
<head>
<script type="text/javascript" src="libraries/p5.js"></script>
<script type="text/javascript" src="libraries/p5.sound.js"></script>
<script type="text/javascript" src="libraries/p5.dom.js"></script>
<script type="text/javascript" src="popup.js"></script>
<style>
body {
width: 250px;
background: beige;
}
</style>
</head>
<body>
<h1>Tell me when to close</h1>
<button id = "5">5 Minute</button>
<button id = "10">10 Minute</button>
<button id = "20">20 Minute</button>
<button id = "30">1/2 Hour</button>
<button id = "60">1 Hour</button>
</body>
</html>
popup.js
document.addEventListener('DOMContentLoaded', function() {
var b1 = document.getElementById('5');
b1.onclick = function() {
let close = chrome.extension.getBackgroundPage();
closeTab(close.tab_id);
};
//continue for others here...
}, false);
function closeTab(tab_id) {
//alert(tab_id);
window.setTimeout(function() {
chrome.tabs.remove(tab_id);
}, 10 * 1000);
}