To be honest, I’m surprised that worked for you, @aecreations. In my testing document.activeElement.ownerDocument.defaultView.focus()
and window.focus()
shared the same (odd) behavior.
As I type this, I have a test extension installed in the sidebar. If I click into the sidebar, then click “Focus main window”, my cursor will appear back in the reply textarea on this site. If I immediately repeat that process, it doesn’t switch back. There seems to be some minimum amount of interaction with the page that is required in order for focus to switch back. Its really quite odd.
manifest.json
{
"name": "Sidebar - focus main window",
"version": "1.0",
"manifest_version": 3,
"sidebar_action": {
"default_panel": "sidebar.html"
},
"content_scripts": [{
"matches": ["<all_urls>"],
"js": ["content.js"]
}]
}
sidebar.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<script defer src="sidebar.js"></script>
</head>
<body>
<input type="text" id="text-input"></input>
<button id="focus-main">Focus main window</button>
</body>
</html>
sidebar.js
const button = document.getElementById("focus-main");
button.addEventListener("click", async () => {
const [tab] = await browser.tabs.query({active: true, lastFocusedWindow: true});
browser.tabs.sendMessage(tab.id, "focus-main");
});
content.js
browser.runtime.onMessage.addListener((message) => {
if (message === "focus-main") {
console.log("focus-main message received");
// document.activeElement.ownerDocument.defaultView.focus();
window.focus();
console.log("doc has focus?", document.hasFocus())
setTimeout(() => console.log("doc has focus?", document.hasFocus()), 100)
}
});