JavaScript 同源策略 - 它如何应用于不同的子域?
-
23-09-2019 - |
题
同源策略如何应用于以下两个域?
如果内容是从 server2 检索的,我可以在 server1 托管的页面上运行 JS 吗?
编辑 根据下面丹尼尔的回答,我可以使用以下命令在不同子域之间包含脚本 <script>
标签,但是异步请求呢?如果我将脚本从 server2 下载到 server1 上托管的页面上会怎样?我可以使用该脚本与 server2 上的服务进行异步通信吗?
解决方案
您只能使用以下命令在不同子域之间包含脚本 <script>
标签,因为它不受该政策的约束。
使用 http://www.example.com/dir/page.html
作为来源(来自 维基百科):
Compared URL Outcome Reason
---------------------------------------------------------------------------------------------
http://www.example.com/dir/page.html Success Same protocol and host
http://www.example.com/dir2/other.html Success Same protocol and host
http://www.example.com:81/dir2/other.html Failure Same protocol and host but different port
https://www.example.com/dir2/other.html Failure Different protocol
http://en.example.com/dir2/other.html Failure Different host
http://example.com/dir2/other.html Failure Different host (exact match required)
http://v2.www.example.com/dir2/other.html Failure Different host (exact match required)
更新:
我可以使用脚本与Server2上的服务不同步吗?
是的,你可以与 JSONP, ,它利用了开放政策 <script>
标签从其他来源检索 JSON。
您可能还需要考虑使用反向代理,如以下 Stack Overflow 帖子中所述:
其他提示
当然,你可以说你插在你的心中永远来自何处运行任何脚本。想想如何插入谷歌地图页面上。
你的描述是一个叫做JSONP模式。凡另一台主机上的服务器返回一个脚本,你在你的页面中插入和脚本调用一个函数在你的页面的响应参数。
不隶属于 StackOverflow