javascript - 当原点不同时从 iframe 获取 url
问题描述
当用户通过单击 iframe 中的链接进行重定向时,我想从 iframe 获取 URL。iframe 的来源与 Web 应用程序不同。
例如:
<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 中有其他站点的支持,并且他们愿意在@박상수 答案中添加代码。
更长的答案:您可以设置一个代理服务器来注入所需的代码来完成这项工作,但是您会遇到法律和道德方面的困难,所以我不打算深入解释如何做到这一点。
另一种方法可能是创建一个浏览器扩展并让您的用户安装它。我应该再次指出,FaceBook 过去曾在采用这种方法时遇到过道德问题。
最终,它们是浏览器阻止您这样做的非常好的安全原因,您可能应该尊重这些原因而不是这样做。
推荐阅读
- javascript - JavaScript 代码不适用于外部文件
- javascript - 单击按钮时如何使用 POST 请求提交表单输入数据?
- android-studio - 在最新检查期间无法捕获任务“:app:processDebugResources”属性“sourceOutputDir”的输出文件快照
- angular - @ngrx/store 生产构建错误:“Store”模板编译期间出错
- javascript - 有没有办法使用 Javascript 函数缩短 URL
- ruby - 如何获得数字之间的特定点
- gitlab - Webook Integration 出现 500 错误,日志中为 Net::OpenTimeout(执行已过期)
- php - 如何修复此查询
- linux - 为什么 KernelStack > ThreadCount*16k
- haskell - 使用 optparse-applicative 生成命令行字符串