首页 > 如何在知乎添加跨域 src 的 <script>?

如何在知乎添加跨域 src 的 <script>?

在知乎的问题

javascript:(function(d){var n=d.getElementsByTagName("head")[0].getElementsByTagName("script").length;var s=d.createElement("script");d.getElementsByTagName("head")[0].appendChild(s);d.getElementsByTagName("script")[n].src="http://www.joyneop.com/blog/js/func.js";})(document)

这样也不行


实现方法

可以用 XHR 跨域获取 JS 内容之后填充到 <script/> 标签内实现,此方法需要你的 JS 文件所在主机先开启 CORS(跨域资源共享,允许白名单中的源页面通过Ajax方式获取本站资源),然后就可以用这段代码跨域注入你的JS了:

javascript:(function(d){var s=d.createElement("script");d.getElementsByTagName("head")[0].appendChild(s);var xhr = new XMLHttpRequest(); xhr.open('GET', 'http://www.joyneop.com/blog/js/func.js', true);xhr.onload = function(){s.innerHTML = xhr.responseText};xhr.send();})(document)

CORS 的设置方法是在服务器端在JS文件的响应头中添加:

Access-Control-Allow-Origin: http://zhihu.com

测试

在你配置好 CORS 之前,上述代码目前还无法生效。测试的话可以用下面这段(html5rocks的所有资源都是允许跨域的):

javascript:(function(d){var s=d.createElement("script");d.getElementsByTagName("head")[0].appendChild(s);var xhr = new XMLHttpRequest(); xhr.open('GET', 'http://www.html5rocks.com/static/js/modernizr.custom.82437.js', true);xhr.onload = function(){s.innerHTML = xhr.responseText};xhr.send();})(document)

以上代码从 html5rocks.com 中获取 Modernizr 代码并注入页面。
执行之前 Modernizr 版本为 2.6.2,执行之后是 2.6.1 了(哎哟SF对图片压缩得真凶残):

【热门文章】
【热门文章】