我只想从 safari 扩展将 jQuery 注入(inject)到网页中。但仅限于某些页面,因为添加 jQuery 作为开始/结束脚本会将其注入(inject)到所有页面,这会导致浏览速度变慢。 我通过使用 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”。有什么想法如何解决这个问题吗?提前致谢!
最佳答案
扩展注入(inject)的脚本无法访问网页的 JavaScript 命名空间。您注入(inject)的脚本创建一个 <script>
元素并将其添加到页面的 DOM 中,然后是 jQuery
脚本实例化的对象属于页面的命名空间,而不是您注入(inject)的脚本的命名空间。
至少有两种可能的解决方案。一、使用扩展 API 以正常方式将 jQuery 注入(inject)页面。仅当您所定位的网页可以使用 URL 模式进行分类时,此方法才可行。
二、使用 Window.postMessage
在注入(inject)的脚本和网页的命名空间之间进行通信。您需要添加另一个 <script>
到页面,并在此脚本中,有一个 message
的监听器事件。监听器将能够使用 jQuery,就好像它是页面本身的“ native ”一样。
如果需要,这里有一些代码可以帮助您入门。
在扩展注入(inject)脚本中:
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);
关于javascript - 从 Safari 扩展将 jQuery 注入(inject)网页,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19203216/