mdmb
mdmb

Reputation: 5283

Chrome extension – popup from the same source?

I'm writing an extension that has a feature to open a URL in a new tab/window. I understand that it will require the user's permission to explicitly allow a "popup".

The content script of that extension is injected into every website, hence the user is required to give the popup permission on every domain they trigger this action on.

Is there a way to avoid it, so the user has to only allow the popup once?

Upvotes: 0

Views: 300

Answers (1)

relentless
relentless

Reputation: 503

Following the excellent lead of wOxxOm, here's a quick example of how you could manage this. The basic idea is to send a message from the content script (which is injected into every website) to the background script, and from there call the chrome.tabs.create method.

contentScript.js

chrome.runtime.sendMessage({message: "openNewTab", urlToOpen: "https://www.example.com/"}, function (response) {
    
});

In the background Script, then, you would have to receive the message and open the desired tab.

chrome.runtime.onMessage.addListener( // this is the message listener
    function(request, sender, sendResponse) {
        if (request.message === "openNewTab")
            openTabFromBackground(request.urlToOpen);
    }
);

async function openTabFromBackground(url){
    chrome.tabs.create({url: url}, function (tab) {});
}

That's it! Here are a few links to the official docs: [https://developer.chrome.com/docs/extensions/mv3/messaging/][1] [https://developer.chrome.com/docs/extensions/reference/tabs/#opening-an-extension-page-in-a-new-tab][2]

I hope I was able to answer your question; if you have any other requests feel free to ask me! This is my first SO answer, so I just hope I didn't break any guidelines ;)

Upvotes: 1

Related Questions