Use case
Browser limitation (Firefox/Chrome) is well documented and explored over the past years. For the given use case, per my understanding closing of a browser tab can only be achieved from a background script, calling chrome.tabs.remove() API.
Browser extension
The approach that seemed logical to me is using the following artifacts.
content.js
document.addEventListener("myCloseTabEvent", function(e){
console.log("[content] originating domain: " + this.domain);
// Prepare message for background script
var myMsgContent = {
type: "myAction",
value: "CloseBrowserTab"}
browser.runtime.sendMessage(myMsgContent);
}, false);
background.js
chrome.runtime.onMessage.addListener(
function(msgData, sender, sendResponse) {
if (msgData.type == "myAction" && msgData.value == "CloseBrowserTab") {
chrome.tabs.remove(sender.tab.id);
} else {
console.log("[background] No action because !(myAction && CloseBrowserTab)");
}
});
Changes to web page to raise the new event
function mySendEvent() {
const myEvent = new Event("myCloseTabEvent"); // OR CustomEvent()
// Dispatch the event
document.dispatchEvent(myEvent);
}
In summary, the following happens:
- The web page loads
- Content script adds the event listener for a custom event
myCloseTabEvent
- Background script adds an onMessage listener using chrome.runtime.onMessage.addListener()
- Once all work is done on the page, existing Javascript code dispatches the custom event by calling
mySendEvent()
.
- Content script runs its listener
function(e)
, sending a message to the background script.
- Background script onMessage listener
function(msgData, sender, sendResponse)
uses the sender object to determine the tabId, and closes the browser tab using chrome.tabs.remove(sender.tab.id);
Questions
- In concept, is this approach the best option we have to achieve the goal of closing the browser tab? Would there be any better ways of achieving the same?
- A background script is require to be able to close the tab (correct me if I'm wrong here). Therefore the browser extension cannot be restricted to be active only on a specific set of domains using content_scripts ->
matches
. What best practices exists to restrict the functionality of the browser extension like this to specific domains? (domain names are known to the users of the extension, but not while packaging the artifacts). This is especially is of interest, to prevent other (malicious) web pages from closing them selves by sending the same message to the background script of the extension.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…