Skip to content

Instantly share code, notes, and snippets.

@hanspinckaers
Last active November 7, 2016 06:27
Show Gist options
  • Save hanspinckaers/b6c251295bc192e5c18591a6b7cf972a to your computer and use it in GitHub Desktop.
Save hanspinckaers/b6c251295bc192e5c18591a6b7cf972a to your computer and use it in GitHub Desktop.
Safari extension - inject a 'before' content script in current tab, indefinitely
<html>
<head>
<script type="text/javascript" charset="utf-8">
// I couldn't find another way to execute a before content script only in a certain Safari tab:
// using dispatching to before script only works in the event 'navigate', which is (imo) too slow for a before contentscript.
// placeholder for the generated content script filename
var currentScriptURL = "";
// set this variable to the tab in which you want to run the script
// e.g. as soon as someone clicks the toolbar button, save the current active tab here.
var currentExternalTab;
safari.application.addEventListener("beforeNavigate", function(event) {
if (currentScriptURL.length > 0) {
safari.extension.removeContentScript(currentScriptURL);
currentScriptURL = "";
}
if (event.target == currentExternalTab) {
var whitelist;
// had more success by generating the following whitelist:
var url = new URL(event.url);
if (url) {
whitelist = ["http://*", "https://*", url.protocol + "//" + url.host + "*"];
} else {
whitelist = [event.url]
}
currentScriptURL = safari.extension.addContentScriptFromURL(safari.extension.baseURI + "inject.js", whitelist, [], false);
}
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment