【问题标题】:How to block external hyperlinks in an iframed page?如何阻止 iframe 页面中的外部超链接?
【发布时间】:2015-02-28 16:47:29
【问题描述】:

我正在制作一个在iframe(跨域)中显示另一个网站的网站。问题是 iframe 中的站点中有外部超链接,我想以某种方式阻止或禁用它们。我只想阻止外部超链接。

即如果iframed页面为example.com/info:

  • 块:<a href="http://other_example.net/pwn">Bad Link</a>
  • 允许:<a href="http://example.com/donate">Good Link</a>

我该怎么做? Greasemonkey 和某种脚本?还是别的什么?

【问题讨论】:

  • 我正在制作的网站不会进入网络。我将在信息屏幕中使用它。
  • 我觉得这个很难。我没有自己的站点或服务器。我不想阻止所有 链接.. 仅在 iframe 中显示的内容之外指向其他地方的链接。
  • 我将把这个 html 文档放到 Firefox 中全屏显示。问题是您可以退出该文档。我为 Firefox 尝试了不同的“白名单”插件,但它不能解决问题。我想阻止该 iframe 内的所有外部链接。不是“home”、“about”等链接,因为它们只是在 iframe 内更改站点。外部链接打开新标签。这就是问题所在。我只想在该 iframe 中显示网站内容。
  • example.com 中没有来自 otherexample.net 的内容。 example.com 的所有内容均来自 example.com 域。

标签: javascript iframe hyperlink greasemonkey


【解决方案1】:

用户脚本或浏览器扩展都可以做到这一点。 Greasemonkey 脚本将在页面上运行,无论它是否在 iframe 中(除非您告诉它不要这样做)。
要阻止外部链接,请将每个链接的 hostname 与 iframed 页面的 hostname 进行比较。

这是一个完整的 Greasemonkey 脚本,它说明了这个过程:

// ==UserScript==
// @name     _Block cross-domain links
// @include  http://www.puppylinux.com/*
// @grant    GM_addStyle
// ==/UserScript==

//-- Only run if the page is inside a frame or iframe:
if (window.top !== window.self) {
    var linkList = document.querySelectorAll ("a");

    Array.prototype.forEach.call (linkList, function (link) {
        if (link.hostname !== location.hostname) {
            //-- Block the link
            link.href = "javascript:void(0)";
        }
    } );

    //-- Mark the links, so the user knows what's up.
    GM_addStyle ( "                             \
        a[href='javascript:void(0)'] {          \
            white-space: nowrap;                \
            cursor: default;                    \
        }                                       \
        a[href='javascript:void(0)']::after {   \
            background: orange;                 \
            content: 'X';                       \
            display: inline-block;              \
            margin-left: 0.3ex;                 \
            padding: 0 0.5ex;                   \
        }                                       \
    " );
}


您可以针对this test page on jsFiddle 安装和运行该脚本。

注意:

【讨论】:

  • 太完美了!谢谢!
【解决方案2】:

为此,您必须使用下面的 Javascript 函数比较您的 url href 属性

// this function will give host name
function get_hostname(url) {
    var m = url.match(/^http:\/\/[^/]+/);
    return m ? m[0] : null;
}

   var hostName =  get_hostname("http://example.com/path");

这将返回http://example.com/,如您的示例输出所示。

使用上述功能,您可以比较您的 URL,如果它与您的主机名匹配 - 那么您可以允许重定向页面,或者您可以显示外部链接的消息

【讨论】:

  • 您希望如何拦截包含外部资源的 iframe 内的链接激活?
  • 我不知道如何使用它。就像我说的,我不熟悉脚本。我不相信这会解决问题。
猜你喜欢
  • 1970-01-01
  • 2013-08-12
  • 2022-01-22
  • 2012-11-22
  • 2016-04-26
  • 2011-11-09
  • 2014-02-09
  • 2011-05-08
  • 2021-11-11
相关资源
最近更新 更多