1

There a few similar questions, but none of them have really gotten at what I'm asking.

I have a browser action popup. In the popup, I want to display settings if you're on a page where the content script has been injected (i.e., any page that matches the matches key within the content_scripts in the `manifest).

If I'm on a page that doesn't match the content_scripts matches pattern (and so wasn't injected), I just want to display a generic message "this plugin activates when you're on so-and-so sites".

What is the cleanest way to do it, without adding any unnecessary permissions?

It seems like one option is sending a message to a content script in the active tab, and seeing if I get a reply, but that seems really.. hacky. I should be able to know just based on a regex if I'm on one of the domains that matches my content script.

I'm looking for something that works in both manifest v2 and v3, btw.

TL;DR;

What's the simplest way to display a "you're on a page that matches your content_script" or "you're not on a page that matches your content_script" in a browser_action popup?

Nathan
  • 73,987
  • 14
  • 40
  • 69

2 Answers2

4

I build chrome extensions full time for an agency and have had projects where I needed to do exactly what you're asking.

The solution can be implemented w/o any permissions whatsoever. I built mine locally with an empty array for permissions. (for mv3)

for popup.html just create 2 divs and have them default to display none.


    <div id="unsupported" style="display: none;">Ooops! This is not a supported site.</div>
    <div id="supported"   style="display: none;">Wohoo! This is a supported site!!!!!</div>

for your script.js, wait till the popup loads then query the active tab in the current window and get that tab's ID to send a message directly to it. If the tab is supported with a content script, it will send a true response (see last code snippet). If it wasn't supported, it will be an 'undefined' response.


async function setUI() {
    
    let tabData = await chrome.tabs.query({ active: true, currentWindow: true })
    let tabId = tabData[0].id // tabs.query returns an array, but we filtered to active tab within current window which yields only 1 object in the array

    chrome.tabs.sendMessage(tabId, {
        'message': 'isSupported'
    }, (response) => {
        console.log(response)
        // response will be true if the message was successfuly sent to the tab and "undefined" if the message was never received (i.e. not supported w/ your content script)
        if (response) return showSupportedHTML()
        // else
        showUnsupportedHTML()
    })

}

function showSupportedHTML() {
    document.querySelector('#supported').style['display'] = ''
}

function showUnsupportedHTML() {
    document.querySelector('#unsupported').style['display'] = ''
}

window.addEventListener('DOMContentLoaded', () => {
    setUI()
})

Lastly, in your content script, add a message listener to receive the message 'isSupported' that comes in from your content script. If the content script receives that message, have it send a response back with 'true'.

chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {

    if (request.message == 'isSupported') {

        console.log('run')
        sendResponse(true)

    }

})

Now, this of course only works for manifest v3 because as far as I know you can't use chrome.tabs.query for mv2. However, I recommend this solution as I've implemented pretty much this exact same code in other projects for clients and it's never had any issues.

I could look into a solution for mv2, though using the "activeTab" permission would be the right way to do it, I believe. Now, if you really don't want to go that route then you could implement a rather hacky solution. For example, you could use window 'focus' and window 'blur' events to see when a user has entered or left a tab. Then set a local storage variable every time a user enters / leaves a supported page. The order of operations for blur and focus is always blur => focus. So, when the blur event occurs you set a local storage variable to false. However, if you leave a supported tab for another supported tab then the 'focus' event will trigger immediately afterwards so you can set that same storage variable back to true.

Now, your content script will load after the tab has been focused so you'll need to add a function for when the page loads. You can run something like document.hidden and if that returns true, do nothing because the user already left this tab. If it returns false, then the user is still on the tab and you can set your local storage variable to true.

When the user opens the popup, you'll check that local storage variable and if its true or false, you can set the UI accordingly.

Let me know if the mv2 solution made sense or sounds too hacky. Happy to look into it more! :)

edit: Here is the code for mv2, I tested it and it does work and without any permissions, other than storage which is not an invasive permission.

Script.js for the mv2 popup:


async function setUI() {

    chrome.storage.local.get(['isSupported'], function (response) { 
        console.log(response['isSupported'])
        // response will be true if the message was successfuly sent to the tab and "undefined" if the message was never received (i.e. not supported w/ your content script)
        if (response['isSupported']) return showSupportedHTML()
        // else
        showUnsupportedHTML()
    })

}

function showSupportedHTML() {
    document.querySelector('#supported').style['display'] = ''
}

function showUnsupportedHTML() {
    document.querySelector('#unsupported').style['display'] = ''
}

window.addEventListener('DOMContentLoaded', () => {
    setUI()
})

code for the content script in mv2:

if (!document.hidden) chrome.storage.local.set({'isSupported': true})

window.addEventListener('blur', () => {
    console.log('left site')
    chrome.storage.local.set({'isSupported': false})
})

window.addEventListener('focus', () => {
    console.log('entered site')
    chrome.storage.local.set({'isSupported': true})
})

Let me know if you have any additional questions.

Jridyard
  • 761
  • 3
  • 9
  • edit: the window.blur and window.focus solution actually does work for mv2! I'll add the code to my original answer. – Jridyard Oct 19 '22 at 02:26
1

Disclaimer: I have no prior browser extension development experience and am just going by the docs. I might be spouting nonsense or giving an answer that is plainly against your requirements, but that would be out of ignorance and not malicious intent. If you find my answer problematic, comment, or cast a vote and move on.

According to MDN, the activeTab permission allows to read the active tab's Tab.url property. One solution could be to request that permission, and then use that API to get the active tab's URL, and then use the same regex from the manifest.json's matches property to test for a match, and then use that information to modify your extension's browser_action UI.

You should be able to read the matches property from the manifest file via the .runtime.getManifest() API. MDN docs, chrome docs.

Snippet to get active tab in a background script: tabs.query({active: true}). (link to MDN docs). A content script should instead use tabs.getCurrent and the Tab.active property of the resolved result.

If you don't want to request the activeTab permission, what you're suggesting with the message-passing between the browser_action scripts and the content scripts might be the right way to go, but I don't know for a fact. The tabs.onActivated event would probably be useful with this approach. Note that to send a message from a background script to a content script, you need to use tabs.sendMessage (MDN docs, chrome docs) instead of runtime.sendMessage.

Another possible (maybe?) approach would be to listen for the tab change in the content script and then send the notification message from the content script to the extension's background scripts via the onfocus event (or similar events), and runtime.sendMessage.

If you go with a messaging-related approach, you might want to put a condition in the content script to only do messaging if the content script is in the top frame of the tab (Ie. iframes don't do messaging), since only one frame of the tab really needs to do this kind of messaging when the active tab changes, and content scripts can be applied to all frames in a browsing context.

Of these possible solutions I can think of, I don't know which is best for you, since you want both minimal permission requirements and a simple/clean approach, and each seems to be a tradeoff.

rainbow.gekota
  • 1,075
  • 2
  • 6
  • 18
  • I appreciate you looking into this even w/o experience with extensions. Using a regex on the tab's URL was one of the first things I thought of, but am hesitant to add that permission-- being able to see all the sites someone is on has a pretty big privacy impact. I didn't know about being able to get the manifest at runtime-- that would be nice instead of hardcoding a regex. I'll look into the other options. It's definitely a shame there isn't a `Tabs.matchesContentScriptsRegex()` function, as that would have been easy to implement and not privacy impacting, but c'est la vie. – Nathan Oct 19 '22 at 00:02
  • fyi I awarded the other comment the bounty, simply because they had direct prior experience with this which is useful to draw on. I still very much appreciate your answer! – Nathan Oct 24 '22 at 20:17