我在访问 Chrome 的标签 ID 时遇到问题。我可以获取它,但它仍保留在扩展程序中,并且我无法在扩展程序之外使用它,尽管我能够在扩展程序之外记录键盘事件。
这是我正在尝试做的事情:
- 用户导航到选项卡并使用“捕获”按钮获取 tabId
- tabId 存储为全局变量
- 然后,用户可以导航到其浏览器中的任何其他选项卡,并从那里使用组合键,用户可以通过同时按 CTRL + SHIFT 在任何给定时刻重新加载捕获的选项卡
扩展名.html
<!DOCTYPE html>
<html>
<head>
<title>Extension</title>
<style>
body {
min-width: 357px;
overflow-x: hidden;
}
</style>
<p>Step 1. Navigate to tab you want to refresh and click the 'capture' button</p>
<button type="button" id="capture">Capture!</button>
<p id="page"></p>
<p>Step 2. Now you can reload that tab from anywhere by pressing CTRL+SHIFT simultaneously</p>
</div>
<script src="contentscript.js"></script>
</head>
<body>
</body>
</html>
清单.json
{
"manifest_version": 2,
"name": "Extension",
"description": "This extension allows you to trigger page refresh on key combinations from anywhere",
"version": "1.0",
"content_scripts": [
{
"matches": ["http://*/*","https://*/*"],
"run_at": "document_end",
"js": ["contentscript.js"]
}
],
"browser_action": {
"default_icon": "icon.png",
"default_popup": "extension.html"
},
"web_accessible_resources": ["script.js"],
"permissions": [
"tabs"
],
}
内容脚本.js
var s = document.createElement('script');
s.src = chrome.extension.getURL("script.js");
(document.head||document.documentElement).appendChild(s);
s.parentNode.removeChild(s);
脚本.js
'use strict';
var isCtrl = false;
var tabId = 0;
document.onkeyup=function(e){
if(e.which === 17) {
isCtrl=false;
}
};
document.onkeydown=function(e){
if(e.which === 17) {
isCtrl=true;
}
if(e.which === 16 && isCtrl === true) {
/* the code below will execute when CTRL + SHIFT are pressed */
/* end of code */
return false;
}
};
document.getElementById('capture').onclick = function(){
chrome.tabs.getSelected(null, function(tab) {
tabId = tab.id;
document.getElementById('page').innerText = tab.id;
});
};
我认为这将是解决方案,但它没有奏效:
/* the code below will execute when CTRL + SHIFT are pressed */
chrome.tabs.getSelected(null, function(tab) {
chrome.tabs.reload(tabId);
});
/* end of code */
作为var tabId = 0;
全局变量似乎毫无意义,所以我认为消息传递应该是解决方案,但问题是我不明白我应该如何实现它。
关于如何根据其 ID 从任何地方刷新选项卡的任何建议?