【问题标题】:Possible to monitor URL clicked inside iframe?可以监控在 iframe 内点击的 URL?
【发布时间】:2021-04-12 11:54:41
【问题描述】:

我需要监控用户何时点击 iframe 的链接并检索点击的 URL。到目前为止,我已经看到了用于检测 iframe 内点击的信息,但没有看到用于检索在该 iframe 内被点击的 a 标签的信息。这可能吗?

【问题讨论】:

  • 在 iframe 文档中添加一个点击事件处理程序,读取 url,然后您可以使用 window.top.onIframeLinkClick(url) 将其传递到顶部窗口,前提是顶部窗口具有函数 onIframeLinkClick 的定义

标签: javascript iframe


【解决方案1】:

这是一个示例代码,用于检索 iframe 被点击的锚元素的 url 到顶部窗口。

Page.html内容

<body>
    <iframe src="./iframe.html" frameborder="1"></iframe>
    <script>
        function onLinkClick(url) {
            // iframe document can access this method with `window.top` namespace
            alert('URL from iframe: ' + url);
        }
    </script>
</body>

iframe.html内容

<body>
    <a href="https://www.google.com/">Google</a>
    <a href="https://in.yahoo.com/">Yahoo!</a>
    <script>
        document.addEventListener('click', function (e) {
            if (e.target.tagName.toLowerCase() == "a") {
                // Stop redirection for demo
                e.preventDefault();
                try {
                    // Pass the url to `window.top.onLinkClick`
                    window.top.onLinkClick(e.target.href);
                } catch (ex) {
                    alert('error: ' + ex.message);
                }
            }
        });
    </script>
</body>

Node.jshttp-server 的帮助下使用http:// 协议测试了此示例,该包从本地文件夹启动服务器。

通过以下命令全局安装http-server

npm i -g http-server

打开命令提示符,导航到提取测试文件的文件夹并运行http-server

在浏览器中打开http://localhost:8080/page.html并测试这个例子。

注意:当通过ftp:// 打开时,该操作被阻止并带有异常Blocked a frame with origin "null" from accessing a cross-origin frame.

【讨论】:

  • 感谢您的回答 - 我不确定您的两段代码是如何组合在一起的,您能否提供一个代码沙箱?非常感谢
  • @cyruslk,我无法创建代码沙箱,因为在线编辑器没有提供写入要加载到 iframe 中的文件的功能。请在ReadMe.md 中找到我的演示here 提供的详细信息。还更新了我的答案的详细信息
  • 我明白你的意思,刚刚测试了你的例子——谢谢。但是,当它来自未在我的本地托管的 iframe(例如:维基百科)时,我如何知道单击了哪些链接以及如何监视网站内的这些内部导航链接?非常感谢您的帮助
  • 在跨域加载时,我们无法使用 JavaScript 访问 iframe 的内容。 HTMLIFrameElement.contentWindowHTMLIFrameElement.contentDocument 这仅使用 same-origin 策略提供 iframe 的窗口或文档参考。
  • 好的,我明白了 - 所以我认为我尝试做的事情不可行。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-08-24
相关资源
最近更新 更多