Last active
November 7, 2016 06:27
-
-
Save hanspinckaers/b6c251295bc192e5c18591a6b7cf972a to your computer and use it in GitHub Desktop.
Safari extension - inject a 'before' content script in current tab, indefinitely
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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