Injecting jQuery to webpage from Safari extension

2019-04-13 08:21发布

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!

1条回答
对你真心纯属浪费
2楼-- · 2019-04-13 08:36

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 the jQuery 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 the message 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:

var s0 = document.createElement('script');
s0.type = 'text/javascript';
s0.src = 'https://code.jquery.com/jquery-2.0.3.min.js';
document.head.appendChild(s0);

var s1 = document.createElement('script');
s1.type = 'text/javascript';
s1.src = safari.extension.baseURI + 'bridge.js';
document.head.appendChild(s1);

window.addEventListener('message', function (e) {
    if (e.origin != window.location.origin)
        return;
    console.log(e.data);
}, false);

window.postMessage('What jQuery version?', window.location.origin);

In bridge.js:

window.addEventListener('message', function (e) {
    if (e.origin != window.location.origin)
        return;
    if (e.data == 'What jQuery version?') {
        e.source.postMessage('Version ' + $.fn.jquery, window.location.origin);
    }
}, false);
查看更多
登录 后发表回答