Cross domain postMessage, identify iFrame - javascript

I use postMessage to send events from an iframe to it's parent document. I have control over both sides but the content comes from two different domains.
My simple problem is, that i can not identify the iFrame inside of it's parent callback method. The implementation looks like this:
In the iFrame:
parent.postMessage(JSON.stringify({action: "closeView" }),'*');
In the parent window:
window.addEventListener('message',function(event) {
if(event.origin !== 'https://example.com')
return;
// Parse message back to json
var messageObject = JSON.parse(event.data);
var source = event.source;
/* this is returning: Window -URL- */
console.log( source );
/* This will throw Permission denied, although this code is inside of "parent" */
console.log(source.parentNode);
},false);
I want to identify a certain parent element of the iframe, which is (logically) inside of the parent document.
When i try to use event.source.parentNode or some jQuery on said object, Firefox says, i can not do this to prevent XSS, error: Error: Permission denied to access property 'parentNode'
How can i get the parent element of the iFrame, that triggered the postMessage event listener?

you can use window names for this, as they pass from iframe tag to iframe context.
parent doc:
<iframe name=fr2 src="data:text/html,%3Chtml%3E%0A%20%3Cscript%3E%20parent.postMessage%28%7Bname%3A%20window.name%7D%2C%20%22*%22%29%3B%3C/script%3E%0A%3C/html%3E"></iframe>
<iframe name=fr3 src="data:text/html,%3Chtml%3E%0A%20%3Cscript%3E%20parent.postMessage%28%7Bname%3A%20name%7D%2C%20%22*%22%29%3B%3C/script%3E%0A%3C/html%3E"></iframe>
<script>onmessage = function(e){ // use real event handlers in production
alert("from frame: " + e.data.name);
};</script>
iframe doc:
<html>
<script> parent.postMessage({name: name}, "*");</script>
</html>
which alerts "fr2", then "fr3".
you can then easily use the name attrib to find the iframe in the parent DOM using attrib CSS selectors.
illustrative demo of window.name+iframe concept: http://pagedemos.com/namingframes/
this painfully simple approach is also immune to issues arising from same-url iframes.

As per my understanding this may be try
here suppose your main window's url is www.abc.com\home.php
<body>
<iframe src="www.abc.com\getOtherDomainContent.php?otherUrl=www.xyz.com"/>
</body>
getOtherDomainContent.php in this file need to write ajax call which get cross url content and push that content in current iframe window(getOtherDomainContent.php)'s body part.
getOtherDomainContent.php
Code:
<html>
<head>
//import jqry lib or other you use.
<script>
$(document).ready({
//getcontent of xyz.com
var otherUrlContent=getAjaxHtml("www.xyz.com");
$("body").html(otherUrlContent);
// further code after content pushed.
//you can easily access "parent.document" and else using parent which will give you all thing you want to do with your main window
});
</script>
</head>
</html>

Like seen in this thread: postMessage Source IFrame it is possible to compare each iframes contentWindow with event.source like this:
/*each(iframe...){ */
frames[i].contentWindow === event.source
But i did not like this too much. My solution for now looks like this:
In the iFrame:
parent.postMessage(JSON.stringify({action: "closeView", viewUrl: document.URL}),'*');
Update:
docuent.URL can become a problem, when you use queries or links with location (#anchor) since your current url will become different from the one of the iframe source. So Instead of document.URL it's better to use [location.protocol, '//', location.host, location.pathname].join('') (Is there any method to get the URL without query string?)
In the parent document:
window.addEventListener('message',function(event) {
if(event.origin !== 'https://example.com')
return;
// Parse message back to json
var messageObject = JSON.parse(event.data);
// Get event triggering iFrame
var triggerFrame = $('iframe[src="'+messageObject.viewUrl+'"]');
},false);
Each event will have to send the current iFrame URL to the parent document. We now can scan our documents for the iFrame with the given URL and work with it.
If some of you know a better way please post your answers.

Related

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.

How do I run code inside an iFrame that was NOT defined in the iframe?

I need to run code as if it were running inside an iframe that is on the page, meaning that when I use window inside that code, it should use the iframe's window object. It is not an iframe I created, so my function is not defined inside it.
var myfunction = function () { // defined in parent, not in the iframe
console.log(window); // window here should be the iframe's window object, not the parent/
window.document.body.appendChild("Appending to iframe body");
}
// Need to somehow run this function inside the iframe
myfunction(); // as if I did this inside the iframe
I need this exact code to run inside the iframe, I know that I can use to fix this myself
frames["FrameName"].document.body.appendChild("Appending to iframe body");
but that won't fix my problem.
This is because I did not write the code myself, there is a module called Opentip that I use to create tool tips. I need to set a tooltip on an element inside the iframe; however, Opentip uses the window object in it's code to be able to create the tooltip properly.
So I need to run
Opentip(myelement, data);
as if I were running it inside the iframe, but without defining it inside the iframe.
So the Opentip function needs to use the iframe window, rather than the parent window.
The code provided is of course untested. This is answer is assuming:
OP circumstances are that the requirements of same origin policy are met.
OP cannot edit the child page directly.
OP cannot use Ajax.
Resources
Dyn-Web
Javascript injected into iframe of same origin not working
Injecting Javascript to Iframe
Snippet
//A//Ref to iframe
var iFrm = document.getElementById('iFrm')
//B//Listen for load event
iFrm.addEventListener('load', function(e) {
//C//Ref to iframe Window
var iWin = iFrm.contentWindow;
//D//Ref to iframe Document
var iDoc = iFrm.contentDocument? iFrm.contentDocument:iFrm.contentWindow.document;
//E//Ref element targeted by Opentip--replace {{>SEL<}} with appropriate selector
var iTgt = document.querySelector({{>SEL<}});
//F//Create, configure, deploy, and inject <script> tag to iframe <head>
var iNode = document.createElement(`script`);
iNode.src = "https://cdn.jsdelivr.net/opentip/2.4.6/opentip-native.min.js";
iDoc.head.appendChild(iNode);
//G//Call Opentip from iframe Window, and hopefully in iframe's context
iFrm.contentWindow.Opentip = function(iTgt, data);
}
/* Notes */
/*//F//Alternative to target iframe <head>:
window.frames["iFrm"].document.getElementsByTagName("head")[0];*/
/*//If not successful in accuirring iframe, try replacing all
"document." with "contentWindow", "contentDocument", or "contentWindow.document"*/
<iframe id="iFrm" name="iFrm" src="/"></iframe>
<!--Optionally you can add an onload event to the iframe itself
<iframe id="iFrm" name="iFrm" src="/"></iframe>
-->

jquery selector from iframe content to object content

I need the following:
I got a html document, in which I have an iframe and an object. Both, the iframe and the object contain separat html files.
Now I want to click a link in the iframe, and this should affect the links inside the object to hide.
How do I use jQuery selectors to select the links in the object html file?
Structure:
<html file parent>
<iframe> html site 1 with link to click</iframe>
<object> html site 2 with links to affect </object>
<html file parent>
Thanks in advance!
This is not possible if the domain of the iframe is different from that of your .
This is a javascript restriction.
For this to possible you need to have control on the url loaded in the iframe.
If it is of same domain then you can probably do that.
If you have control over the iframe's url try this.
First, have a look at window.postMessage. Using this, you may send an event from your iframe to the window parent target. Listening for that event in the window parent (when something in your iframe changed), you will then be able to access any element inside the object tag using a syntax like this:
$('object').contents().find('linkSelector')
Give your iframe an id, let's say myIframe:
<iframe id="myIframe"> html site 1 with link to click</iframe>
Get a reference to the iframe:
var myIframe = document.getElementById('myIframe');
Post a message from iframe:
myIframe.contentWindow.postMessage('iframe.clicked', 'http://your-domain.here.com');
Handler for iframe change:
var handleIframeChange = function(e) {
//
if(e.origin == 'http://your-domain.here.com') {
// Get reference to your `object` tag
var objContent = $('object').contents();
// For instance, let's hide an element with a class of `link-class-here`
objContent.find('.link-class-here').hide();
}
}
Listen on parent window for the event sent by the iframe:
window.addEventListener('iframe.clicked', handleIframeChange, false);
Haven't tested it right now (did this in the past, when I had control over iframe) but it should work, but as I said, only if you can have control over the iframe.

Passing Messages from iFrame Across all Browsers

I have an embed-able iframe that will be used on 3rd party sites. It has several forms to fill out, and at the end must inform the parent page that it is done.
In other words, the iframe needs to pass a message to it's parent when a button is clicked.
After wading through oceans of "No, cross-domain policy is a jerk" stuff, I found window.postMessage, part of the HTML5 Draft Specification.
Basically, you place the following JavaScript in your page to capture a message from the iframe:
window.addEventListener('message', goToThing, false);
function goToThing(event) {
//check the origin, to make sure it comes from a trusted source.
if(event.origin !== 'http://localhost')
return;
//the event.data should be the id, a number.
//if it is, got to the page, using the id.
if(!isNaN(event.data))
window.location.href = 'http://localhost/somepage/' + event.data;
}
Then in the iframe, have some JavaScript that sends a message to the parent:
$('form').submit(function(){
parent.postMessage(someId, '*');
});
Awesome, right? Only problem is it doesn't seem to work in any version of IE. So, my question is this: Given that I need to pass a message from an iframe to it's parent (both of which I control), is there a method I can use that will work across any (>IE6) browser?
In IE you should use
attachEvent("onmessage", postMessageListener, false);
instead of
addEventListener("message", postMessageListener, false);
The main work-around I've seen used involves setting a hash value on the parent window and detecting the hash value in the parent, parsing the hash value to obtain the data and do whatever you want. Here's one example of doing that: http://www.onlineaspect.com/2010/01/15/backwards-compatible-postmessage/. There are more options via Google like this one: http://easyxdm.net/wp/.
This is way simpler than that.
You say you control both the parent and the content of the frame you can set up two way
communication in javascript.
All you need is
yourframename.document.getElementById('idofsomethinginttheframe')
And then from inside the frame address anything outside it with
parent.document

Selecting an element in iframe with jQuery

In our application, we parse a web page and load it into another page in an iframe. All the elements in that loaded page have their token IDs. I need to select the elements by those token IDs. Means - I click on an element on the main page and select corresponding element in the page in the iframe. With the help of jQuery I'm doing it in the following way:
function selectElement(token) {
$('[tokenid=' + token + ']').addClass('border');
}
However with this function I can select the elements in the current page only, not in the iFrame. Could anybody tell me how can I select the elements in the loaded iFrame?
Thanks.
var iframe = $('iframe'); // or some other selector to get the iframe
$('[tokenid=' + token + ']', iframe.contents()).addClass('border');
Also note that if the src of this iframe is pointing to a different domain, due to security reasons, you will not be able to access the contents of this iframe in javascript.
Take a look at this post: http://praveenbattula.blogspot.com/2009/09/access-iframe-content-using-jquery.html
$("#iframeID").contents().find("[tokenid=" + token + "]").html();
Place your selector in the find method.
This may not be possible however if the iframe is not coming from your server. Other posts talk about permission denied errors.
jQuery/JavaScript: accessing contents of an iframe
when your document is ready that doesn't mean that your iframe is ready too,
so you should listen to the iframe load event then access your contents:
$(function() {
$("#my-iframe").bind("load",function(){
$(this).contents().find("[tokenid=" + token + "]").html();
});
});
If the case is accessing the IFrame via console, e. g. Chrome Dev Tools then you can just select the context of DOM requests via dropdown (see the picture).
here is simple JQuery to do this to make div draggable with in only container :
$("#containerdiv div").draggable( {containment: "#containerdiv ", scroll: false} );

Categories