I just want to inject jQuery into a webpage from a safari extension. But only to some pages because adding jQuery as a start-/endscript would inject it to all pages and this makes browsing slow. I tried it by creating a script tag using its onload function:
var node = document.createElement('script');
node.onload = function(){
initjquerycheck(function($) {
dosomethingusingjQuery($);
});
};
node.async = "async";
node.type = "text/javascript";
node.src = "https://code.jquery.com/jquery-2.0.3.min.js";
document.getElementsByTagName('head')[0].appendChild(node);
to check if jquery is loaded i use:
initjquerycheck: function(callback) {
if(typeof(jQuery) != 'undefined'){
callback(jQuery);
}else {
window.setTimeout(function() { initjquerycheck(callback); }, 100);
}
}
But typeof(jQuery) remains undefined. (checked that using console.log()). Only if I call console.log(typeof(jQuery)) from the debugging console it returns 'function'. Any ideas how to fix that? Thanks in advance!
Extension injected scripts cannot access the web page's JavaScript namespace. Your injected script creates a
<script>
element and adds it to the page's DOM, but then thejQuery
object instantiated by the script belongs to the page's namespace, not to your injected script's.There are at least two potential solutions. One, inject jQuery into the page the normal way, using the extension API. This method is only viable if the web pages that you are targeting can be categorized using URL patterns.
Two, use
Window.postMessage
to communicate between your injected script and the web page's namespace. You will need to add another<script>
to the page, and in this script, have a listener for themessage
event. The listener will be able to use jQuery as if it were "native" to the page itself.Here's some code to get you started, if needed.
In the extension injected script:
In bridge.js: