Reputation: 33
I'm making a website that shows another website in an iframe
(cross-domain). The problem is that there are external hyperlinks in the site in the iframe, and I want to somehow block or disable them. I want to block ONLY external hyperlinks.
That is, if the iframed page is example.com/info
:
<a href="http://other_example.net/pwn">Bad Link</a>
<a href="http://example.com/donate">Good Link</a>
How can I do this? Greasemonkey and some kind of script? Or something else?
Upvotes: 3
Views: 3406
Reputation: 93473
Either a userscript or a browser extension can do this. A Greasemonkey script will run on a page, irregardless of whether it's in an iframe (unless you tell it not to).
To block external links, compare each link's hostname
to the iframed page's hostname
.
Here's a complete Greasemonkey script that illustrates the process:
// ==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; \
} \
" );
}
You can install and run that script against this test page on jsFiddle.
Note:
waitForKeyElements()
.Upvotes: 1
Reputation: 3495
For this you have to compare your url href
attribute using Javascript function as below
// 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");
This will return http://example.com/ as in your example output.
Using above function you can compare your URL and if its going to mathch with your host name - then you can allow to redirect the page or else you can show message for external Links
Upvotes: 0