Javascript: Get domain in iframe - javascript

Is it possible for me to get the domain from an iframe for example like:
<iframe src="http://www.google.com/search&etc...so on"></iframe>
So by using javascript, i could get only "google.com" and redirect the iframe to blank. Below is idea (in python coding, idk if it correct or not, but just an idea) for anyone wishes to help me.
for iframe in page:
if re.search("(google.com)", iframe, re.IGNORECASE):
iframe = iframe.replace('<iframe src=""></iframe>')

You could search for all iframes in your page and then get the ones that have google.com as source :
var iFrames = document.getElementsByTagName("IFRAME");
for (var i = 0; i < iFrames.length; i++) {
if (iFrames[i].src.indexOf("google.com") != -1) {
// do here whatever you want, for example clearing the iframe's src:
iFrames[i].src = "";
}
}

​var iFrames = document.getElementsByTagName('IFRAME');
for (var iFrameIndex = 0; iFrameIndex < iFrames.length; iFrameIndex++) {
// Match Google iFrames
if (iFrames[iFrameIndex].src.test(/google\.com/)) {
// Set such iFrames src to a blank string
iFrames[iFrameIndex].src = '';
}
}
​
Here is a working JSFiddle

My answer pertains to JavaScript, as per your tagging. Yes, it's possible to get the domain. However there is a very important rule. If the iframe is 1) a different domain than the parent page AND 2) the iframe changes to a different page/domain after the first load... then you can't see the new page/domain.
Lets say you have an index.html page on yourdomain.com and you want to have an iframe which loads Google:
<!doctype html>
<html>
<body>
<div><iframe src="http://www.google.com"></iframe></div>
</body>
</html>
When your index page first loads, you will be able to see that the domain is google.com. However, if a user performs a Google search, you will not be able to see the new URL. This is a security feature of browsers where you cannot see any activity of an external domain within an iframe. Furthermore, if a person clicks on a Google search result to even another domain, you cannot see the new domain. The URL will always appear to be http://www.google.com. Hope that helps.
I see others have already posted examples... but thought I'd put a jQuery example because it might help somebody out there:
$('iframe[src*="google.com"').attr('src', '');

Related

How to call an iframe in JS so that the original url is maintained in the address bar

I am looking for a way in JAVASCRIPT (possibly using iframes), to keep the url of an original site when a new page appears. Example: original site url shows www.initialPage.com. When the user clicks ALT-Z, the new website should show the content of www.secondaryPage.com. The code I thought would work looks like below. However, when ALT-Z is selected, www.initialPage.com stays in the url (which is what I want) but only a blank page shows.
document.addEventListener('keydown', function(e) {
if (e.altKey) {
switch (e.code) {
case 'KeyZ':
function prepareFrame() {
var ifrm = document.createElement("iframe");
ifrm.setAttribute("src", "http://www.secondaryPage.com");
ifrm.style.height = "100vh"
ifrm.style.width = "100vw"
document.body.replaceWith(ifrm);
}
prepareFrame();
break;
}
}
});
Is there something I forgot in the function to allow www.secondaryPage.com to display? I know there are security risks but this is for a very small trusted private network
I've done a lot more experimentation on this and it seems the reason the site with the iframe (www.secondaryPage.com) does not display has something to do with the initial page (www.initialPage.com) is a secure site. When I use an un-secure site as the initial page, the secondaryPage is displayed just fine. If anyone can provide some insight as to what I can do to have the above code work while on a secure site, I would appreciate it.

Allowing two sites to communicate to know the current URL of an iframe

I'm trying to figure out a solution to allow an website to know what URL the user is on through an iframe.
Website 1: http://website.website.com (Remote Website, can only add javascript & html to the webpage)
Website 2: https://example.com (Fully Editable, php, html, js.. etc)
Current Code: (Of Website 2 (Example.com)
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" lang="en-US" prefix="og: http://ogp.me/ns# fb: http://ogp.me/ns/fb#">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>Website.com</title>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
</head>
<body class="body_blank">
<script type="text/javascript">
jq = jQuery.noConflict();
jq(document).ready(function() {
var currentFramePath = '';
var iframe = '<iframe src="{src}" id="#iFrameContainer" style="position:fixed; top:0px; bottom:0px; right:0px; width: 100%; border: none; margin:0; padding:0; overflow: hidden; z-index:999999; height: 100%;">';
var urlFrame = getUrlParameter('currentFrame');
if(urlFrame != null && urlFrame != ''){
console.log("Frame not found");
jq('#iFrameContainer').html(iframe.replace('{src}', urlFrame));
currentFramePath = urlFrame;
}
jq('#iFrameContainer').click(function(){
console.log("Clicked in frame");
currentFramePath = jq(this).attr('href');
console.log(currentFramePath);
});
setInterval(function(){
window.location = window.location.href.split('?')[0] + '?currentFrame=' + currentFramePath;
console.log("Update Query");
}, 5000);
});
function getUrlParameter(sParam) {
var sPageURL = decodeURIComponent(window.location.search.substring(1)),
sURLVariables = sPageURL.split('&'),
sParameterName,
i;
console.log("Get Query");
for (i = 0; i < sURLVariables.length; i++) {
sParameterName = sURLVariables[i].split('=');
if (sParameterName[0] === sParam) {
return sParameterName[1] === undefined ? true : sParameterName[1];
}
}
};
</script>
<div id="wrapper" class="wrapper_blank">
<iframe src="http://website.website.com" id="#iFrameContainer" style="position:fixed; top:0px; bottom:0px; right:0px; width: 100%; border: none; margin:0; padding:0; overflow: hidden; z-index:999999; height: 100%;">
</div>
</body>
</html>
Problem
If I refresh the page (iframe) on example.com it refreshes and forgets the page that the user is/was on...
As you can see I have attempted to get it working by detecting their page through an iFrame however this is impossible due to it being on a different domain.
Solution?
I'm looking for some sort of solution to do something like described below, bare in mind there could be a better solution.
I want the website website.website.com to get the current path / url of the page the user is on (which is being viewed through an iframe) and for it to send this path/url through to example.com then example.com would update the session / temporary cookie / temporary local storage / variable... etc which would then mean it would adjust the query string to point itself to the correct URL for when the user refreshes their page resulting in the refresh correctly remembering the page they were on.
Attempt
I tried to use the postMessage function by putting the follow code on their respective sites:
Website 1 Extra Code
<script type="text/javascript">
setInterval(function() {
parent.postMessage(window.location.pathname, "https://website.com");
},1000);
</script>
Website 2 Extra Code:
var eventMethod = window.addEventListener ? "addEventListener" : "attachEvent";
var eventer = window[eventMethod];
var messageEvent = eventMethod == "attachEvent" ? "onmessage" : "message";
eventer(messageEvent, function(e) {
console.log('Parent Message: ', e.data);
}, false);
However nothing happens, no console messages or errors... just nothing.
I've even tried copying the likes of https://blog.teamtreehouse.com/cross-domain-messaging-with-postmessage but nothing in that helped :(
Any ideas what I am doing wrong and a way to resolve it to achieve this?
Thanks
Edits
I've tried the following js inside http://website.website.com but it didn't work:
localStorage.setItem('CurrentURLChecker', window.location.href)
if (localStorage.getItem('CurrentURLChecker')) {
if (window.parent.location.href == "https://website.com/" ) {
console.log("URL FOUND");
}
}
Uncaught DOMException: Blocked a frame with origin "http://website.website.com" from accessing a cross-origin frame at http://website.website.com/:251:44
EDIT - An example
Website 1 = "http://stackoverflow.serviceprovider.com"
Website 2 = "https://stackoverflow.com"
Website 2 contains an iframe which shows the exactly what Website 1 shows.
I am never going to visit Website 1, all clicks are done on Website 2
If I was to click on a link inside the iframe and it was to navigate to: http://stackoverflow.serviceprovider.com/this-new-page/ then Website 1 should be able to detect this and store the iframes location and remember it.
Now if I refresh my browser instead of the iframe loading http://stackoverflow.serviceprovider.com it would instead load the page they actually refreshed which is http://stackoverflow.serviceprovider.com/this-new-page/
The tab/window URL will always stay on https://stackoverflow.com/ but it would be a necessity to append a query string so the links can be made sharable.
It's that simple.
For security reasons, you can only get the url for as long as the contents of the iframe, and the referencing javascript, are served from the same domain.
If the two domains are mismatched, you'll run into cross site reference scripting security restrictions.
Since you can add javascript to the website 1 (http://website.website.com) you could create a session with javascript and save the current page the user visits in the cookies (as described here). When the user visits the home page of website on (which is happening, when the user reloads the website 2) you could get this value with javascript and load the saved page (window.location.href = 'http://website.website.com/YourSavedPage').
If you don't want that redirection every time the user visits the home page of website 1, you could think about creating a own page to redirect the user to the last opened page and to open that page once, when the iframe is loaded.
It seems like the targetOrigin (second argument of postMessage) may simply not match. Do not forget that the protocol, host & port must all be an exact match.
From the markup you posted, the iframe src domain is http://website.website.com while the parent domain is https://example.com.
If you wish for http://website.website.com to communicate it's URL to https://example.com then posting a message from the iframe should read:
window.parent.postMessage(window.location.pathname, 'https://example.com');
To make sure that the targetOrigin filter is not what's causing communication issues you can also use * for testing.
It seems that you are doing the opposite in your example (passing source domain instead of target domain) and it's also very misleading that you use "website 1" to reference the embedded site and "website 2" to reference the parent site in your explanation: I would expect the opposite.
The code samples with http://website.website.com and https://example.com doesn't work because there are on different URI schemes. One is http and another is https.
So, they have to be on the same HTTP protocol for this to work(either both http or both https).
In my example, I am using parent window URL as https://parent.example.com and iframe URL as https://child.somesite.com.
In iframe Site Code:
When the iframe site loads, we are going to send a postMessage() to the parent site about the current URL by assigning event listeners using addEventListenerto anchor tags, whenever they are clicked.
So, when an anchor tag is clicked, we prevent the default flow of route, send a message about current URL to the parent window and set current window href to the anchor's href.
Code:
var a_tags = document.getElementsByTagName('a');
for(var i=0;i<a_tags.length;++i){
a_tags[i].addEventListener('click',function(event){
event.preventDefault();
var current_href = this.getAttribute('href');
var new_location = current_href.match(/^http(s)?:\/\/.+$/) !== null ? current_href : window.location.origin + current_href;// be careful about leading '/' when dealing with relative URLs.
window.parent.postMessage(new_location,'https://parent.example.com');
window.location.href = new_location;
});
}
In parent window code:
Here, we will just attach an event listener to message event and check if the event was fired from our child site itself using the referrer present in event.origin.
If it's not, we return. If it is, we update our localStorage and set the URL received to the iframe_url key.
While refreshing the page, we first check if localStorage has this key set or not. If not, we load iframe as is, else, we load the URL we have in our storage by setting it's src attribute.
Note that we make an iframe element from javascript to avoid attaching separate event handlers to deal with it's src when requested on a new tab in the window.
Code:
const IFRAME_SITE_DOMAIN = 'https://child.somesite.com';
window.addEventListener('message',function(event){
if(event.origin !== IFRAME_SITE_DOMAIN) return;
localStorage.setItem('iframe_url',event.data);
});
var iframe = document.createElement('iframe');
if(localStorage.getItem('iframe_url') === null){
iframe.setAttribute('src',IFRAME_SITE_DOMAIN);
}else{
iframe.setAttribute('src',localStorage.getItem('iframe_url'));
}
iframe.setAttribute('height','500');
iframe.setAttribute('width','500');
document.body.append(iframe);
Sharable Links:
We make a button and span for sharable user actions like so.
Code:
<button id='share_resource_state'>Share Link</button>
<span id='share_url'></span>
Now, we add the iframe's current URL in URL fragments(characters after #). Since we are adding this in a fragment, we need not worry about it's effect on server side of parent site as it is never sent to the server and plays a role purely on the client's browser.
We convert the iframe's URL to base64 using btoa() while sharing and decode it using atob() when requested on a new tab or window.
This changes the current code on parent site(main window) a bit like so.
Code:
const IFRAME_SITE_DOMAIN = 'https://child.somesite.com';
window.addEventListener('message',function(event){
if(event.origin !== IFRAME_SITE_DOMAIN) return;
localStorage.setItem('iframe_url',event.data);
});
var iframe = document.createElement('iframe');
if(localStorage.getItem('iframe_url') === null){
if(window.location.hash != ''){
try{
var decoded_string = atob(window.location.hash.substring(1));// to remove the # from the fragment and get the base64 encoded data.
if(decoded_string.indexOf('iframe_url=') !== -1){
iframe.setAttribute('src',decoded_string.split('=')[1]);// we split the string based on '=' and assign the iframe URL which was set at the time of sharing
}else{
iframe.setAttribute('src',IFRAME_SITE_DOMAIN); // we don't deal with the fragment at all since it isn't encoded for our iframe purpose.
}
}catch(e){
iframe.setAttribute('src',IFRAME_SITE_DOMAIN); // we don't deal with the fragment at all.
}
}else{
iframe.setAttribute('src',IFRAME_SITE_DOMAIN); // we set URL as is.
}
}else{
iframe.setAttribute('src',localStorage.getItem('iframe_url'));
}
iframe.setAttribute('height','500');
iframe.setAttribute('width','500');
document.body.append(iframe);
document.getElementById('share_resource_state').addEventListener('click',function(){
var iframe_sharable_url = localStorage.getItem('iframe_url') === null ? IFRAME_SITE_DOMAIN : localStorage.getItem('iframe_url');
document.getElementById('share_url').innerHTML = window.location.href.split('#')[0] + '#' + btoa('iframe_url=' + iframe_sharable_url);
});
Some pointers before we start, whenever you have a problem it is always good to check the following basics first.
Basic problem solving
Make a bare minimum proof of concept that only shows the problem and nothing else. Remove all extra markup, styling and code.
Make sure your libraries are up to date (you are using jquery 1.11.3 instead of 3.3.1).
Follow standards, conventions, best practices if you are swimming upstream you only make it harder on yourself.
Best practices used in this answer
You are advised to follow these, they are called best practices because they make life easier not harder.
script tags go at the bottom of the page
encapsulate all your own scripts with a self executing function block in order not to pollute the global namespace
using the popular and well known $ as the jQuery reference so that everyone understands each other
using use strict javascript directive will warn about problem areas in advance
terminology
parent - refers to the main document in the browser window with the iframe markup
child - refers to the document inside the parent's iframe
Cross frame access - the answer
Access child document from the parent document
To access the child document from the parent iframe we use iframe.contentWindow. Once we have the iframe window we gain access to the child document with iframe.contentWindow.document
Access parent document from the child document
To access the parent iframe from the child document we use window.frameElement. Once we have the parent iframe element we can access the parent document with window.frameElement.ownerDocument.
The basic example
Unfortunately your examples are so convoluted with numerous problems outside the scope of this question that I was compelled to re-create these pages in order to facilitate as examples.
These examples show retrieving both the child and parent location from either the child or the parent and visa versa.
The Parent - test.html
Notice the span ids parentOut and childOut which gets populated with jQuery.
<!DOCTYPE html>
<html>
<head>
<title>Website.com</title>
</head>
<body>
<h1>Parent page</h1>
<span>Parent location: <span id="parentOut"></span></span><br>
<span>Child location: <span id="childOut"></span></span><br>
<div id="wrapper">
<iframe src="test_child.html" id="#iFrameContainer" width="100%" height="300"></iframe>
</div>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script>
// script encapsulation
(function ($) { "use strict";
// jQuery ready
$(function() {
$('#parentOut').text(document.location);
$('#childOut').text($('iframe')[0].contentWindow.document.location);
// the iframe by tag name
console.log($('iframe')[0]);
// the iframe by id
console.log($('#iFrameContainer')[0]);
// the iframe window
console.log($('iframe')[0].contentWindow);
// the child document
console.log($('iframe')[0].contentWindow.document);
});
})(jQuery);
</script>
</body>
</html>
The Child - test_child.html
Notice the span ids parentOut and childOut which gets populated with jQuery. There are also several hyperlinks of pages that WON'T work, see topic Security policies.
<!DOCTYPE html>
<html>
<head>
<title>Website.com</title>
</head>
<body>
<h1>Child page</h1>
<span>Child location: <span id="childOut"></span></span><br>
<span>Parent location: <span id="parentOut"></span></span><br>
<h3>Some child pages that DON'T work</h3>
SecurityError: Protocols, domains, and ports must match.<br>
SecurityError: Protocols must match.<br>
X-Frame-Options SAMEORIGIN<br>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script>
// script encapsulation
(function ($) { "use strict";
// jQuery ready
$(function() {
$('#childOut').text(document.location);
$('#parentOut').text(window.frameElement.ownerDocument.location);
// parent iframe
console.log(window.frameElement);
// parent document
console.log(window.frameElement.ownerDocument);
});
})(jQuery);
</script>
</body>
</html>
Being notified of child location changes
To be notified of location changes on the child document we can use the events onload or onloadstart to notify the parent.
$(document).on('load' function (event) {
$(window.frameElement.ownerDocument).append($('<p>').text('The location changed to:'+this.location);
});
Security policies
As we can see this functionality is quite powerful as it completely exposes both the parent and child documents to each other and visa versa. Because this allows you access to manipulate the content there are security policies in place to prevent us from manipulating the integrity of content that we do not own.
Protocols, domains, and ports must match
There is slightly different wording for similar errors but they all boil down to the child page must have the same domain name, same port and use the same protocol as the parent or access is blocked. The first two examples on the child page will return these errors respectively.
SecurityError: Blocked a frame with origin "http://127.0.0.1:1221" from accessing a frame with origin "http://my.umt.edu". Protocols, domains, and ports must match.
SecurityError: Blocked a frame with origin "http://127.0.0.1:1221" from accessing a frame with origin "https://en.wikipedia.org". The frame requesting access has a protocol of "http", the frame being accessed has a protocol of "https". Protocols must match.
These pages are allowed to be viewed in an iframe but if and only if the children are located at http://127.0.0.1:1221 (in my case) will this functionality be allowed.
Even further security
We can also completely prevent our sites from being viewed in an iframe. By means of the X-Frame-Options http response header, if configured with SAMEORIGIN the browser will refuse the page from being loaded in the frame. See last example on child page.
Conclusion
It is much simpler to find out exactly what the problem is if we set our project aside and start again with only the problem pieces. This also makes it much easier for someone to assist and provide a useful answer.
From what I understand of your use case, what you want to do is not allowed. You can freely make use of frames on your own site with your own pages but it is not allowed to manipulate someone else's content.
nJoy!
Just a though, based on the assumption that you can access and edit to the second website yet the server does not support PHP or any other programming/scripting language and you're stuck with HTML and Javascript:
In the parent PHP page which you are embedding the iframe into, you could call the iframe with an added parameter as shown bellow:
<iframe src="http://website.website.com/example.html?parent=<?=$_SERVER['HTTP_REFERER'];?>"></iframe>
Then in the child html page you can catch the parameter passed with the GET method with JavaScript or jQuery and use it for your purpose of determining the page, as bellow:
<script>
$(document).ready(function(){
var urlParams = new URLSearchParams(window.location.search);
var parentPage = urlParams.get('parent'); //which will store "https://example.com" in the variable. Now that you have the parent page URL you can manipulate it.
});
</script>
Even if you can't edit the html, you can inject JavaScript and HTML to the DOM of the iframe page through parent page and have it immediately run by declaring it within a jQuery function like so:
(function() {
var urlParams = new URLSearchParams(window.location.search);
var parentPage = urlParams.get('parent');
})();
I hope this made at least a little bit of sense, and can be helpful in any way. Good luck with your quest.
Cheers!
1, you need iframe show the same url even after reload
2, iframe and parent cross origin
3, you can inject js in iframe pages
4, parent page fully in control
check out https://github.com/postor/iframe-url-remember
npm i && npm run start and visit http://localhost:3000
postMessage works, I will explain in detail later, I have to catch a bus
I use node to serve static and mimic cross origin, so you can use nginx apache or php serve to host the public folder, and use lan IP and localhost mimic cross origin, you may need to modify some src
public/js/index.js is for parent page
window.addEventListener("message", receiveMessage, false);
function receiveMessage(event) {
console.log(event)
localStorage.setItem('iframesrc', event.data)
}
var src = localStorage.getItem('iframesrc')
src && (document.getElementById('iframe').src = src)
1.listen to message event, whenever new url comes write it into localStorage
2.on page load, read url from localStorage and modify src of iframe
public/js/iframe.js for the pages inside iframe
window.parent.postMessage(location.href, '*');
1.on page load, send url to parent page
it's easy and working
you can use cookie instead of localstorage then you can use php update iframe src before sending to client browser
or php session, you may need to trigger an ajax to notify server whenever url change
You could use a tracking pixel and pass the current path of the iframe as parameter:
var pathname = window.location.pathname;
var d = new Date();
var imageUrl = 'http://www.example.com/trackingpixel.php?path='
+ pathname + '&time=' + d.getTime();
var img = document.createElement('img');
img.src = imageUrl;
document.body.appendChild(img);
And in the parent domain, create the route trackingpixel.php and save the current path in the session:
if( !isset($_SESSION['time']) || ($_GET['time'] > $_SESSION['time'])) {
$_SESSION['time'] = $_GET['time'];
$_SESSION['path'] = $_GET['path'];
}
Then when you reload the page, you can get the path from the session:
if(isset($_SESSION['path'])) {
$iframeUrl = $_SESSION['path'];
}
else {
$iframeUrl = 'http://website.website.com';
}
Note that these is a slight chance this is not going to work if the reload is executed before the tracking pixel from the previous load.
PS: Nowadays ad block extensions are quite popular and they may prevent the pixel from "firing up", I would advice to test whether the pixel works with some of the popular extensions.

Preventing second static HTML page from loading

I have a link on a page. When the user clicks the link a static HTML page loads. I would like to prevent the user from launching a second instance of the same static HTML document.
I'm thinking some javascript up front in the static HTML page might do. Basically if the script detects that there is already an instance of the static HTML document loaded then a Javascript pop-up would indicate to the user that 'document is already loaded" (something like that).
Anyhow, Java script is not my strong point so wondering if someone can please shed some light on this.
I'm not sure if this is cross-browser, but works in Chrome:
var wins = {};
var anchors = document.getElementsByTagName('a');
for(var i=0, len=anchors.length; i<len; i++) {
anchors[i].onclick = function(e) {
e.preventDefault();
var href = this.href;
if(wins[href]) {
wins[href].focus();
} else {
wins[href] = window.open(href);
}
}
}
http://jsbin.com/ivabax/1/edit
You could implement a logging feature that tracks each link that was clicked and maintains a session for the current user. If the link has already been clicked then you could present your firewall window that says "Sorry, this link has already been accessed".
So the hyperlink the user would click would first hit a tracking mechanism before being allowed (or not allowed) to continue to the URL in question.

How can i remove the http header referer informations(saved by browser) using javascript?

For example, there is a "Link" called go to view at the bottom of the my page, which is redirecting to http://localhost/test.php.
If we use $_SERVER['HTTP_REFERER'] in test.php page it will display the url of the page from which link was clicked.
The problem is this: my URL can be seen at the target page. This needs to be avoided. How can i do this using javascript?
When JavaScript gets to it, it is too late. Plus JavaScript can not do it.
There is no cross-browser solution. For example this code works in Chrome, but not in FF:
classic html link<br/>
js trickery
<script>
function goto(url) {
var frame = document.createElement("iframe");
frame.style.display = "none";
document.body.appendChild(frame);
frame.contentWindow.location.href="javascript:top.location.href = '" + url + "';";
}
</script>
There are third party solutions. You can find any number of them by searching "referer hide" or "refer mask" with you favorite search engine. - Some of them look sady, so try to find a trustworty one.
On the other hand. This is part of Internet culture. Referers can be used for valuable statistics for example. And if your website is in a crawler's index, they can find the link anyway.
Check http://www.referhush.com/
As sentence on this site says :"Webmasters can use this tool to prevent their site from appearing in the server logs of referred pages as referrer."

Telling when an iframe is on a new URL

I am using JavaScript to make a small iframe application, and I cannot seem to figure out a way to update the URL in my URL bar I made when someone clicks a link inside the iframe.
It needs to be instantaneous, and preferably without checking every millisecond whether or not the value of document.getElementById('idofiframe').src has changed.
I can't seem to find a simple property to tell when the url has changed, so if there is not one, then solving this programmatically will work as well.
Thanks for the help!
This will be difficult to do because it is considered xss and most browsers block that.
There are most likely some workarounds involving AJAX.
First of all, what you want to do will be possible only if the source of your iframe points to the same domain as the parent window. So if you have a page page.html that iframes another page iframed.html, then both of them have to reside on the same domain (e.g. www.example.com/page.html and www.example.com/iframed.html)
If that is the case, you can do the following in the iframed.html page:
<script type="text/javascript">
window.onload = function() {
var links = document.getElementsByTagName('a');
for (var i=0, link; link = links[i]; i++) {
link.onclick = function() {
window.parent.location.href = '#' + encodeURIComponent(this.href);
}
}
}
</script>
This will make it so that whenever you click on a link in iframed.html, the url bar will put the url of the link in the "hash tag" of the url (e.g. www.example.com/page.html#http%3A%2F%2Fwww.example.com%2FanotherPage.html)
Obviously, you would have to have a script like this on every page that is to appear inside the iframe.
Once this is in place, then you can put this snippet inside of page.html, and it will make the iframe automatically load the url in the hash tag:
window.onload = function() {
var url = window.location.hash.substr(1);
if (url) {
document.getElementById('iframe').src = url;
}
}
I unfortunately haven't run this code to test it, but it is pretty straight forward and should explain the idea. Let me know how it goes!
You could add an onload event to the iframe and then monitor that - it'll get thrown whenever the frame finishes loading (though, of course, it could be the same URL again...)
Instead, can you add code to the frame's contents to have it raise an event to the container frame?
In IE, the "OnReadyStateChanged" event might give you what you want.

Categories