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} );
Related
Is it possible in Vue.js (or just plain old js) to detect when an iframe (that contains content from another domain) has changed? Here is the more precise scenario:
I load a page that contains an iFrame with content from another domain
The user clicks a button (or does something) inside that iframe, which changes the content inside the iframe
Can I somehow detect that change?
I don't want to affect or change any of the content inside the frame, just detect that it has changed. Is this possible?
Ok, I figured out a way to make this work for my needs. I set a counter which gets updated on every onload event (which I figured out gets fired when someone submits a form inside my iframe), then make my changes to the surrounding page:
const iframe = document.querySelector('#myframe')
iframe.onload = () => {
this.formloadCounter += 1
console.log('iframe has been loaded:' + this.formloadCounter + ' times.')
if (this.formloadCounter>1) {
//do stuff
}
}
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.
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.
I want to get an element from an iFrame and click it. Getting the element succeeded. Unfortunately i cant get the element within the iframe clicked. Anyone with a solution?
Thanks!
$(document).ready(function(){
var frame = $('#f314dbebb8'); //ID from the frame
console.log(frame);
});
Is this what you are trying with
document.getElementById('iframeResult').contentWindow.document.getElementById('buttonId').click()
where iframeResult is Id of iframe and buttonId is Id of element to be clicked ??
Do you mean you are trying to "click it" programmaticly, like via JavaScript? Or a user interaction like with your mouse and cant?
If you are trying via JavaScript its not going to work. Look up something called "same origin security". JavaScript cannot access other pages load via an iframe for security purposes. http://javascript.info/tutorial/same-origin-security-policy
Have you tried document.getElementById('elementid').click();?
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