【发布时间】:2020-03-21 08:22:40
【问题描述】:
当用户通过单击 iframe 中的链接进行重定向时,我想从 iframe 获取 URL。 iframe 的来源与网络应用不同。
例如:
<iframe src="startingUrl" class="embed-responsive-item" id="iframe" sandbox="" allowfullscreen</iframe>
我在 iframe 上添加了一个负载侦听器,以检测用户何时重定向到此 iframe 中的其他 url:
const iframe = document.getElementById("iframe");
iframe.addEventListener("load", (evt) => {
const location = iframe.contentWindow.location;
console.log(location); // this gives me a Location object where I can see the href property
console.log(location.href); // this gives me a SecurityError: Permission denied to get property "href" on cross-origin object, I also tried to get a copy of the object but that doesn't work either.
});
我知道是什么导致了这个问题,我也知道这是不可能的。但我需要找到一种方法来获取页面的当前 URL。如果这不行,那么我希望使用此 Web 应用程序的用户可以复制 iframe 的 url 并将其放在输入字段中。
现在他们可以在 chrome 中执行“查看框架源”和此框架:在 Firefox 中查看框架源或信息。但这对用户来说太复杂了。有没有办法让他们在 iFrame 中看到 URL,或者让用户更简单地获取 URL。
iFrame 中的网站不是我的。
非常感谢所有帮助!
【问题讨论】:
-
iframe 的来源是否在您的控制之下?如果是这样,您可以考虑
postMessage。 -
不,不是...谢谢
-
也许这个答案中的某些东西可以帮助你:stackoverflow.com/questions/938180/get-current-url-from-iframe
-
是的,我已经读过了,但它不起作用。
-
如果您没有 CORS 访问他们的页面,那么您无法检测到该页面上的事件。
标签: javascript html iframe same-origin-policy