How to get the parent protocol from within an iFrame using javascript? - javascript

I have two CDN domains, one that delivers content over https and the other one through http. And I'm creating a widget (inside an iframe) that could be used in a variety of domains and sometimes in secure pages and sometimes not.
Is there a way to infer using JavaScript the parent's protocol from within the widget's iFrame ?

I figured it out, if I ommit the protocol in the iframe of my widget then it will inherit the protocol of the parent, eg:
In my widget html:
<script>document.write("my protocol is " + document.location.protocol);</script>
The iframe code that points to my widget (to insert into the other sites):
<iframe src="//my-widget.example.com/widget"></iframe>
This requires my-wdiget.example.com/widget to work for both secure and unsecure connections (ie: http://my-widget.example.com/widget and https://my-widget.example.com/widget should both point to the same content) but that's OK because in my situation the only domains I don't have control over are the ones used as CDN.

You can get informations from the main window just using:
window.parent.

Related

JQuery: Select div under iframe with JQuery

I'm trying to select a div used in an iframe, but the select instruction always return an empty object, any idea how to solve this please:
console.log($(this).contents().find('div'));
JSFiddle: https://jsfiddle.net/8jxvry4c/6/
Div is not accessible because it is not part of your DOM but part of iframe which itself consist different DOM for some other place.
In order to get div of iframe, you need to fetch all content of iframe and then find the div you wanted.
Following code can be used to fetch iframe content but it should be within same domain if not it will throws cross domain error
$('iframe').contentWindow.document.body.innerHTML
Or you can use cross-document messaging in Javascript where message is sent to iFrame and iFrame respond accordingly.
Main page
myIframe.contentWindow.postMessage('hello', '*');
iframe
window.onmessage = function(e){
if (e.data == 'hello') {
alert('It works!');
}
};
You can refer this link for more detail.
There are also some plugin available to perform these kinds of task more swiftly.
You can't access to DOM of a different domain because of Same-origin policy
Under the policy, a web browser permits scripts contained in a first
web page to access data in a second web page, but only if both web
pages have the same origin.
This policy prevents a malicious script on one page from obtaining
access to sensitive data on another web page through that page's
Document Object Model.
But you can accomplish this on server side of course performming a GET/POST request. And again you can't perform a GET/POST request from javascript (ajax) unless the other domain have Access-Control-Allow-Origin header.

Access iframe node given element node inside iframe using Javascript only

Say I'm given an HTML element node, such as a
<div id = "content"></div>
and that's contained in an iframe. It's passed in to me as a node. I want to be able to get the iframe node that the element's in -- there's no specific id and I want to be able to access it just from the element node. I've tried
elNode.window
and
elNode.parent
But obviously that gives me undefined. I'm also passed in the current window, but trying
curWindow.parent
just passes me in the window, so that was led to no avail. I really just want to get the iframe from the element node. If anyone has any pointers, that's much appreciated.
this issue is due to the same-origin policy: the browser won’t allow the original script to inspect the contents of the cross-origin document. more details about sop https://en.wikipedia.org/wiki/Same-origin_policy. Generally, there are following ways to solves this issue:
using element has never really been subject to the same-origin policy: it will download and execute any script, regardless of origin.
cross-document messaging,allows a script from one document to pass textual messages to a script in another document, regardless of the script origins. Calling the postMessage() method on a Window object results in the asynchronous delivery of a message event (you can handle it with an onmessage event handler function) to the document in that window.
Cross-Origin Resource Sharing https://www.w3.org/TR/cors/ : This draft standard extends HTTP with a new Origin: request header and a new Access-Control- Allow-Origin response header. It allows servers to use a header to explicitly list origins that may request a file or to use a wildcard and allow a file to be requested by any site.
To support multi domain websites of this sort, you can use the domain property of the Document object . But, the domain value must have at least one dot in it; you cannot set it to “com” or any other top-level domain. for example ecar.car.com, pcar.car.com. you can set the domain to car.com.
hope this can give you a kind of help

"Friendly iFrame" detection: How can I find my nested iframe in the top page?

I've come across a challenging iFrame detection problem in a "friendly iframe" environment. I need to identify from window.top which foreign domain iframe element in window.top.document loads inside of itself yet another iframe with the same domain, protocol, and port as window.top.
So here's the central question: On Page A, how can you determine in JavaScript that iFrame B contains iFrame C? Again, Page A and iFrame C are of the same domain, protocol and port and can communicate with each other. iFrame B is on a different domain. I want to find the DOMElement that is associated with iFrame C on Page A.
Possible things that have been tried that have not worked:
document.referrer matching. Page A matches the src attribute of all iframes on Page A to the document.referrer property in iFrame C. Unfortunately, this doesn't work if multiple iframes on Page A load content with the same src on iframe B. It also doesn't work if the src attribute of iframe B is about:blank or javascript:something.
window.location.hash communication by looking at the src attributes of iframes. Page A can't get the window.location.hash of iFrame B, so no luck there.
This has to work in IE 6 and 7, so there is no window.postMessage support. Sorry.
Additional information:
This is a configuration called "Friendly iFrames". Friendly iFrames (FIF) are common in the advertising industry. Here's how they work:
A page on publisher site, say Page A foo.com, injects iframe B from some-random-ad-server.com. Then inside of iframe B on some-random-ad-server.com, another iframe C is loaded from foo.com. So:
I have access (i.e. DOM manipulation) to Page A from iFrame C. Page A has access to iFrame C.
Nothing on the Page A or iFrame C has access to iFrame B.
I realize this is old, but I was curious about client side solutions and ran across this post. I'm using server-side to handle this, why not use server side as last resort? Granted referrer is sketchy on server side, however when dealing with iframed pages, the referrer is pretty reliable and can be compared against the host of the local application and the referring application.
Here is how I've done it in ASP.NET/C# (same thing can be done in PHP, etc)
// set referrer
if (Request.UrlReferrer != null && Request.Url.Host != Request.UrlReferrer.Host)
{
Session["Referrer"] = Request.UrlReferrer.OriginalString;
}

Javascript: error in access IFrame on local files

I use some iframes in my page and I'd like to access iframe elements from parent page and the opposite.
From the parent page I add Iframes with:
<iframe id="iframe1" src="./iframe1.html" width="100%" height="100%"></iframe>
and I try di access iframe element by javascript with:
window.frames['iframe1']
...
From iframes I use something like
//to get elements
var obj = parent.document.getElementById('iframe1');
//to call methods
parent.document.mymethod();
In both situation it give me the following error:
Unsafe JavaScript attempt to access frame with URL file:///C:/Users/marco/test/iframe1.html from frame with URL file:///C:/Users/marco/test/index.html. Domains, protocols and ports must match.
I know that file have to be in the same domain. The problem is that I don't call files from web server, but browser has to read files directly from resource path. This because I will put theese files embedded in an Android app and I will read them with a webview from local resources.
I tried to set manually window.domain = 'mydomain' but nothing changed and also to use absolute path for iframes.
I use Sencha Touch, if it can be usefull.
Any ideas?
Thanks for your time,
Marco

Accessing an element outside of iframe

I have a file: 1.html and an iframe inside it.
I want to access an element (lets say myelement) which exists in 1.html (outside of iframe) from the iframe.
How can I do that?
I tried:
top.getElementById("myelement")
top.document.getElementById("myelement")
parent.getElementById("myelement")
parent.document.getElementById("myelement")
but it didn't work!!
Communication between an iframe and parent document is not possible for cross-origin resources. It will only work if the iframe and the containing page are from the same host, port and protocol - e.g. http://example.com:80/1.html and http://example.com:80/2.html
For cross-origin resources, you can make use of window.postMessage to communicate between the two, but this is only useful if the browser supports this method and if you have control over both resources.
Edit - assuming both resources are from the same origin
In the iframe, window.parent refers to the global object of the parent document, not the document object itself. I believe you would need to use parent.document.getElementById
Assuming that same origin policy is not a problem, you can use parent.document to access the elements, and manipulate them.
Demo here, source of outer frame here, source of iframe here.
parent.document Not working
For cross-origin resources, you can make use of window.postMessage to communicate between the two, but this is only useful if the browser supports this method and if you have control over both resources.
Communication between an iframe and parent document is not possible
for cross-origin resources
that is in so many ways wrong, i dont even WANT to know where to begin. Of course cross-domain requests and algorith-exchanges have a long history, it is both well documented and working now, one might start JSON-request or even simple XMLHttp-Requests via JQuery, for example, you can even load whole .js-files AND inject them into your code - injecting code in remote sources will of course need an appropriate interface; one may achieve such a thing via communication with the responsible persons, just ask them nicely and maybe they'll cooperate if your project makes sense and has its use.
To answer the question : accessing whole documents would raise the need for transferring it beforehand - i would recommend XML for that purpose because the DOM-tree and XML are nearly interchangeable. Load the tree via .get (.ajax for remote hosts), append it to this and access it just like you want ... sounds easy and if you got some experience it IS easy. If you ever read "cross-domain" and "not possible" in the same sentence again you might as well ignore the poster - there are many people out there who dont know what they're talking about ;-)

Categories

Resources