在我的扩展中,我创建了一个小的弹出窗口:
"browser_action": {
"default_popup": "popup.html"
},
然后将一些 JavaScript 注入到活动选项卡中加载的页面。它应该改变光标形状并注册一个“onclick”事件。
它工作正常,但是,用户需要单击页面/选项卡两次。第一次单击将焦点转移到页面/选项卡,只有第二次单击由 onclick 处理程序处理。同样,光标形状 ( style.cursor = 'crosshair'
) 仅在第一次单击后发生变化。
如何自动将焦点转移到选项卡?我已经尝试过chrome.tabs.update({"active":true});
,但这不起作用。
清单.json
{
"manifest_version": 2,
"name": "Stack Overflow",
"version": "1.0",
"browser_action": {
"default_popup": "popup.html"
},
"permissions": [
"tabs",
"activeTab"
]
}
popup.html
<!doctype html>
<!--
This page is shown when the extension button is clicked, because the
"browser_action" field in manifest.json contains the "default_popup" key with
value "popup.html".
-->
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Question</title>
<script src="popup.js"></script>
</head>
<body>
<div>How to transfer focus to the tab?</div>
</body>
</html>
popup.js
document.addEventListener('DOMContentLoaded', function () {
chrome.tabs.executeScript({ "file": "page.js" });
chrome.tabs.update({"active":true});
return;
});
page.js
// The cursor is not updated until I click the tab.
document.body.style.cursor = 'crosshair';
document.addEventListener('click', function(){alert('you clicked me')});