Keith
Keith

Reputation: 4204

How do I run my Chrome extension once on load?

I have a Chrome extension that's currently opening up a side-menu when clicked. That works alright so far, but I'm trying to bind it to a key. That works fine, but only after I've clicked the button at least once, since that's when it injects the JS from the background JS page

chrome.browserAction.onClicked.addListener(clicked)

Calls:

var opened = [];

function clicked(tab){
    var currentTabId = tab.id;
    if(opened.indexOf(currentTabId) < 0){
        opened.push(currentTabId);

        chrome.tabs.executeScript({
            file: 'jquery.js'
        });
        chrome.tabs.insertCSS({
            file: 'admin.css'
        });
        chrome.tabs.executeScript({
            file: 'admin.js'
        });
    } else {
        chrome.tabs.executeScript({
            code: 'admin.toggle();'
        });
    }
}

This all works great. Admin.js also listens for the tilde ~ button to open up the side-drawer, too (it calls the same admin.toggle() function). But the problem is I need to inject the JS before the first button click, so it knows to listen for the ~.

Can I still do this using a browserAction? Or would I need to use a content script instead?

Thanks in advance!

Upvotes: 0

Views: 636

Answers (1)

gkalpak
gkalpak

Reputation: 48212

The browser action get's triggered when the user clicks the browser-action button. So there is no way (and no point) to trigger it programmatically.

You are already using content scripts (files and code injected by means of executeScript) are content scripts (just programmatically injected).

If you want to have the functionality available "right away" you need to inject some content scripts automatically when the user navigates to a new web-page.

One way to achieve this is through the content_scripts property in manifest.json.

If you don't want to inject jQuery and admin.js in every web-page (especially if your script is "heavy", e.g. registering lots of event-listeners etc), you could inject a tiny script to listen for ~ and only then unregister the listener, inject your scripts and execute admin.toggle().

Upvotes: 1

Related Questions