我正在制作一个在 iframe
中显示另一个网站的网站(跨域)。问题是 iframe 中的站点有外部超链接,我想以某种方式阻止或禁用它们。我只想阻止外部超链接。
也就是说,如果 iframed 页面是 example.com/info
:
- block :
<a href="http://other_example.net/pwn">Bad Link</a>
- 允许:
<a href="http://example.com/donate">Good Link</a>
我该怎么做? Greasemonkey 和某种脚本?还是别的?
最佳答案
用户脚本或浏览器扩展都可以做到这一点。 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 安装并运行该脚本.
注意:
- 包含的页面是 fiddle.jshell.net/9aQv5/3/show/ .
- iframed 页面是 www.puppylinux.com .
- 当您运行该脚本时,外部链接将被禁用,并且被禁用的链接标有“X”。
- 此方法适用于简单的静态页面。对于 AJAX 驱动的页面,使用
waitForKeyElements()
.
关于javascript - 如何阻止 iframed 页面中的外部超链接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27740714/