jquery selector from iframe content to object content - javascript

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.

Related

How would you get a src from an iframe within an iframe?

I have some code that in short, is opening an iframe (let's call it iframe1) to view a pdf file, and that pdf is being shown in an iframe itself (let's call it iframe2), I would like to be able to get the source of the iframe2 that is within an iframe1 that would be opened so that the iframe1 itself is just the src of the pdf iframe2 and not 2 different iframes. The Url's are very different.
what is the best way to do this?
I have an open_iframe function that looks something like
function open_iframe(url) {
return '<iframe id="iframe" src="' + url + '" width=100% height=100% frameborder="0" allowfullscreen></iframe>';
}
and I am writing another function that is
function find_file_url(url) {
let iframe = this.open_iframe(url);
return iframe.contentWindow.document.getElementsByTagName('iframe')[0].src;
}
I also have Jquery available to use as well.
Is this something that's possible?
Is there a better approach?
Thanks in advance!
have you attached the iframe object to your dom?
In this the html tag for "iframe" instead of creating a html string , you can create the dom iframe object directly and assign attributes to them and then parse it further.
As Barmar said until then it would considered as just a html string.
.document.getElementsByTagName('iframe') will be a null element as it is not attached to document object.
You might try document.domain = "site.com" , I'm dealing with similar issue.
This will ensure they are in the same domain
Also you can use iframe.contentWindow and iframe.contentDocument scripting to communicate inside for the nested frame.
also assign onload, errorOnload to the attributes for console tracking
iFrame onload JavaScript event
https://javascript.info/cross-window-communication

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>
-->

Cross domain postMessage, identify iFrame

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.

GetElementById form a "master" inside an iframe

Ok this is in javascript, so I have a iframe inside a contente place holder of a master page.
Something like this.
1-MasterPage
2-contentePlaceHolder
3-Iframe
When i'am in the iframe how do I get a control with "GetElementById" from the masterPage??
Unfortunately, you cannot. Your iFrame is unaware of the master page holding it.
If both your parent page and iframe src are on the same domain then using JQuery you can do something like this from the iframe's src page:
$(parent.document).find('#myElement').hide('slow');
Try this :
Provided that masterpage and iframe src belong to same domain , let's say you have a button in iframe , on 'onclick' event of that button write this code :
var P = parent.document.getElementById("element_id") ;

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