Question

In my extension, I need to perform actions when the toolbar icon is clicked. However, there are a lot of scripts and stylesheets involved, so I want to avoid using plain "content scripts", because those are always going to be loaded into every page a user visits, slowing down their browser. Instead, I want to inject the scripts only after the button is clicked.

The docs only say the following:

If you need the command [i.e., a toolbar button click] to initiate an action in an injected script, respond to the command in the global HTML page or an extension bar and send a message to the script.

In Chrome, you can use chrome.tabs.executeScript()

In Firefox, you can use tabs.activeTab.attach()

How do you do it in Safari?

Was it helpful?

Solution

You can use the following four methods to conditionally inject content into pages:

safari.extension.addContentScript
safari.extension.addContentScriptFromURL
safari.extension.addContentStyleSheet
safari.extension.addContentStyleSheetFromURL

Documentation here.

However, note that these methods will not inject content into any already existing tabs at the time you call them. Therefore, they may not be suitable for your use case. You could use one of these methods and then reload the tab, but you may not want that because of the jarring user experience.

Instead, you may need to use a technique like this: Have a very lightweight content script that gets injected into every page, whose only job is to listen for messages from the extension's global page and, when instructed, to create the appropriate <script> and <style> or <link> elements for the content you want to inject. Then, when your toolbar button is clicked, have the global page pass the appropriate message to the content script, perhaps including the URLs of the desired content.

A drawback of this approach is that the injected scripts (the ones you add by creating <script> tags) will not be able to communicate directly with the global page or with other parts of the extension. If you need them to communicate, they will need to do so using window.postMessage or some other technique.

Here's a minimal example. Assume your extension has a toolbar item that issues the command "inject-content".

In the global page:

safari.application.addEventListener('command', function (evt) {
    safari.application.activeBrowserWindow.activeTab.page.dispatchMessage(evt.command);
}, false);

In the always-injected content script:

safari.self.addEventListener('message', function (evt) {
    if (evt.name == 'inject-content') {
        var myScriptTag = document.createElement('script');
        myScriptTag.src = safari.extension.baseURI + 'my_script.js';
        document.body.appendChild(myScriptTag);
    }
}, false);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top