从Safari扩展注入jQuery到网页

我只是想从一个safari扩展中将jQuery注入一个网页。 但仅限于某些页面,因为将jQuery添加为start- / endscript会将其注入所有页面,这会使浏览速度变慢。 我通过使用onload函数创建脚本标记来尝试它:

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); 

检查是否加载了jquery我使用:

 initjquerycheck: function(callback) { if(typeof(jQuery) != 'undefined'){ callback(jQuery); }else { window.setTimeout(function() { initjquerycheck(callback); }, 100); } } 

但是typeof(jQuery)仍未定义。 (使用console.log()检查)。 只有从调试控制台调用console.log(typeof(jQuery)),它才会返回’function’。 任何想法如何解决? 提前致谢!

扩展注入的脚本无法访问网页的JavaScript命名空间。 您注入的脚本会创建一个元素并将其添加到页面的DOM中,但是脚本实例化的jQuery对象属于页面的命名空间,而不是您注入的脚本。

至少有两种可能的解决方案。 一,使用扩展API以正常方式将jQuery注入页面。 只有在您定位的网页可以使用url格式进行分类时,此方法才有效。

二,使用Window.postMessage在注入的脚本和网页的命名空间之间进行通信。 您需要在页面中添加另一个 ,并在此脚本中为该事件提供一个侦听器。 监听器将能够使用jQuery,就好像它是页面本身的“本机”一样。

如果需要,这里有一些代码可以帮助您入门。

在扩展注入脚本中:

 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); 

在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);