javascript 如何解决 parent.document 中的问题“阻止了一个带有原点的框架访问带有原点的框架”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22041367/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 22:16:20  来源:igfitidea点击:

How to resolve issue "Blocked a frame with origin from accessing a frame with origin" in parent.document

javascriptjqueryiframefancybox

提问by n92

I have popup fancybox iframeopens on clicking a button in my site, I have two urls to access the site

我在我的网站上点击了一个按钮,弹出了fancybox iframe,我有两个网址可以访问该网站

1. www.xyz.com
2. xyz.com

On clicking on a button a pop up will appear, In that page i am getting the parent page URL as follows

单击按钮时会出现一个弹出窗口,在该页面中,我将获得父页面 URL,如下所示

parent.document.title

which works fine in first URL(www.xyz.com), But in second URL(xyz.com), it throws a JavaScript error as follows

它在第一个 URL 中工作正常(www.xyz.com),但在第二个 URL 中(xyz.com),它会抛出一个 JavaScript 错误,如下所示

Uncaught SecurityError: Blocked a frame with origin "www.xyz.com" from accessing a frame with origin "xyz.com". Protocols, domains, and ports must match.  

Basically, I want to retrieve the parent page title, How to do this using jquery/javascript

基本上,我想检索父页面标题,如何使用 jquery/javascript

回答by ZachRabbit

What you have to do is make sure the iframe isn't loading from the other domain name. If you've written the HTML for the iframe, it would need to change from something like this:

您需要做的是确保 iframe 没有从其他域名加载。如果您已经为 iframe 编写了 HTML,则需要从以下内容进行更改:

<iframe src="http://www.xyz.com/iframe/page.html"></iframe>

To something like this:

对于这样的事情:

<iframe src="/iframe/page.html"></iframe>

Doing it that way makes sure the URL requested will always be from the current domain name, and it should work as intended. It's the same idea if you're using a plugin that grabs the URL from a link. Take off the domain so it loads from the current one.

这样做可以确保请求的 URL 始终来自当前域名,并且应该按预期工作。如果您使用的是从链接中获取 URL 的插件,则情况相同。取下域,使其从当前域加载。