In my extension I create a small popup window:
"browser_action": {
"default_popup": "popup.html"
},
and then inject some JavaScript to the page loaded in the active tab.
It is supposed to change the cursor shape and register an 'onclick' event.
It works fine, however, the user needs to click the page/tab twice.
The first click transfers the focus to the page/tab, and only the second click is handled by the onclick handler.
Likewise, the cursor shape (style.cursor = 'crosshair'
) changes only after the first click.
How can I transfer focus automatically to the tab?
I have tried chrome.tabs.update({"active":true});
but that does not work.
manifest.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')});
Copyright Notice:Content Author:「Andrew Dwojc」,Reproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/48509133/transfer-focus-to-a-tab-in-a-chrome-extension