contentDocument.document returning undefined [duplicate] - javascript

I'm trying to get the document object of an iframe, but none of the examples I've googled seem to help. My code looks like this:
<html>
<head>
<script>
function myFunc(){
alert("I'm getting this far");
var doc=document.getElementById("frame").document;
alert("document is undefined: "+doc);
}
</script>
</head>
<body>
<iframe src="http://www.google.com/ncr" id="frame" width="100%" height="100%" onload="myFync()"></iframe>
</body>
</html>
I have tested that I am able to obtain the iframe object, but .document doesn't work, neither does .contentDocument and I think I've tested some other options too, but all of them return undefined, even examples that are supposed to have worked but they don't work for me. So I already have the iframe object, now all I want is it's document object. I have tested this on Firefox and Chrome to no avail.

Try the following
var doc=document.getElementById("frame").contentDocument;
// Earlier versions of IE or IE8+ where !DOCTYPE is not specified
var doc=document.getElementById("frame").contentWindow.document;
Note: AndyE pointed out that contentWindow is supported by all major browsers so this may be the best way to go.
http://help.dottoro.com/ljctglqj.php
Note2: In this sample you won't be able to access the document via any means. The reason is you can't access the document of an iframe with a different origin because it violates the "Same Origin" security policy
http://javascript.info/tutorial/same-origin-security-policy

This is the code I use:
var ifrm = document.getElementById('myFrame');
ifrm = (ifrm.contentWindow) ? ifrm.contentWindow : (ifrm.contentDocument.document) ? ifrm.contentDocument.document : ifrm.contentDocument;
ifrm.document.open();
ifrm.document.write('Hello World!');
ifrm.document.close();
contentWindow vs. contentDocument
IE (Win) and Mozilla (1.7) will return the window object inside the
iframe with oIFrame.contentWindow.
Safari (1.2.4) doesn't understand that property, but does have
oIframe.contentDocument, which points to the document object inside
the iframe.
To make it even more complicated, Opera 7 uses
oIframe.contentDocument, but it points to the window object of the
iframe. Because Safari has no way to directly access the window object
of an iframe element via standard DOM (or does it?), our fully
modern-cross-browser-compatible code will only be able to access the
document within the iframe.

For even more robustness:
function getIframeWindow(iframe_object) {
var doc;
if (iframe_object.contentWindow) {
return iframe_object.contentWindow;
}
if (iframe_object.window) {
return iframe_object.window;
}
if (!doc && iframe_object.contentDocument) {
doc = iframe_object.contentDocument;
}
if (!doc && iframe_object.document) {
doc = iframe_object.document;
}
if (doc && doc.defaultView) {
return doc.defaultView;
}
if (doc && doc.parentWindow) {
return doc.parentWindow;
}
return undefined;
}
and
...
var el = document.getElementById('targetFrame');
var frame_win = getIframeWindow(el);
if (frame_win) {
frame_win.targetFunction();
...
}
...

In my case, it was due to Same Origin policies. To explain it further, MDN states the following:
If the iframe and the iframe's parent document are Same Origin, returns a Document (that is, the active document in the inline frame's nested browsing context), else returns null.

Related

Restore native Window method

For a script I'm writing, I'd like to use the native window.open method. However, a script already loaded to which I don't have access, overwrites the global window.open method with a boolean (ouch).
I know how to restore the methods on the Document (via HTMLDocument.prototype), but I don't know how to restore them on the Window, as I can't seem to find the equivalent for that to Window. Window.prototype.open does not exist for example.
I have tried creating an iframe, and getting the open method from that contentWindow in the iframe, but the browser will block opening windows using open because it was probably created in another origin. Neither delete open; does work because open was defined using var in the globally loaded script.
So, how can I restore the open method, defined as 'native code' in Chrome?
I know there are similar questions around, but actually the main question is:
Is there a equivalent of HTMLDocument for the Window object?
I've found this question and the accepted answer (using an iframe) could be used in your case.
The only issue is you can only use the retrieved version of window.open as long as the iframe is still in your document.
function customOpen() {
// local variables definitions :
var url = "https://stackoverflow.com", iframe, _window;
// creating an iframe and getting its version of window.open :
iframe = document.createElement("iframe");
document.documentElement.appendChild(iframe);
_window = iframe.contentWindow;
// storing it in our window object
window.nativeOpen = _window.open;
try {
window.open(url);
} catch (e) {
console.warn(e); // checking that window.open is still broken
}
window.nativeOpen(url);
// deleting the iframe :
document.documentElement.removeChild(iframe);
}
document.getElementById("button").addEventListener("click", customOpen);
Another JSFiddle
Keeping the workaround answer in case someone needs it :
Can you execute a custom script prior to the execution of the script that redefines window.open? If so, you could create a copy of the window.open in another global variable.
It could look like this :
1. First : a backup script
window.nativeOpen = window.open;
2. Then, whatever the window.open overwriting script does :
window.open = false; // who does that, seriously?
3. Your window opening script, that'll use your window.open copy :
function customOpen() {
var url = "https://stackoverflow.com";
try {
window.open(url);
} catch (e) {
console.warn(e);
}
window.nativeOpen(url);
}
JSFiddle example

How to determine if JS code executes in iframe? [duplicate]

I am writing an iframe based facebook app. Now I want to use the same html page to render the normal website as well as the canvas page within facebook. I want to know if I can determine whether the page has been loaded inside the iframe or directly in the browser?
Browsers can block access to window.top due to same origin policy. IE bugs also take place. Here's the working code:
function inIframe () {
try {
return window.self !== window.top;
} catch (e) {
return true;
}
}
top and self are both window objects (along with parent), so you're seeing if your window is the top window.
When in an iframe on the same origin as the parent, the window.frameElement method returns the element (e.g. iframe or object) in which the window is embedded. Otherwise, if browsing in a top-level context, or if the parent and the child frame have different origins, it will evaluate to null.
window.frameElement
? 'embedded in iframe or object'
: 'not embedded or cross-origin'
This is an HTML Standard with basic support in all modern browsers.
if ( window !== window.parent )
{
// The page is in an iframe
}
else
{
// The page is not in an iframe
}
I'm not sure how this example works for older Web browsers but I use this for IE, Firefox and Chrome without an issue:
var iFrameDetection = (window === window.parent) ? false : true;
RoBorg is correct, but I wanted to add a side note.
In IE7/IE8 when Microsoft added Tabs to their browser they broke one thing that will cause havoc with your JS if you are not careful.
Imagine this page layout:
MainPage.html
IframedPage1.html (named "foo")
IframedPage2.html (named "bar")
IframedPage3.html (named "baz")
Now in frame "baz" you click a link (no target, loads in the "baz" frame) it works fine.
If the page that gets loaded, lets call it special.html, uses JS to check if "it" has a parent frame named "bar" it will return true (expected).
Now lets say that the special.html page when it loads, checks the parent frame (for existence and its name, and if it is "bar" it reloads itself in the bar frame. e.g.
if(window.parent && window.parent.name == 'bar'){
window.parent.location = self.location;
}
So far so good. Now comes the bug.
Lets say instead of clicking on the original link like normal, and loading the special.html page in the "baz" frame, you middle-clicked it or chose to open it in a new Tab.
When that new tab loads (with no parent frames at all!) IE will enter an endless loop of page loading! because IE "copies over" the frame structure in JavaScript such that the new tab DOES have a parent, and that parent HAS the name "bar".
The good news, is that checking:
if(self == top){
//this returns true!
}
in that new tab does return true, and thus you can test for this odd condition.
The accepted answer didn't work for me inside the content script of a Firefox 6.0 Extension (Addon-SDK 1.0): Firefox executes the content script in each: the top-level window and in all iframes.
Inside the content script I get the following results:
(window !== window.top) : false
(window.self !== window.top) : true
The strange thing about this output is that it's always the same regardless whether the code is run inside an iframe or the top-level window.
On the other hand Google Chrome seems to execute my content script only once within the top-level window, so the above wouldn't work at all.
What finally worked for me in a content script in both browsers is this:
console.log(window.frames.length + ':' + parent.frames.length);
Without iframes this prints 0:0, in a top-level window containing one frame it prints 1:1, and in the only iframe of a document it prints 0:1.
This allows my extension to determine in both browsers if there are any iframes present, and additionally in Firefox if it is run inside one of the iframes.
I'm using this:
var isIframe = (self.frameElement && (self.frameElement+"").indexOf("HTMLIFrameElement") > -1);
Use this javascript function as an example on how to accomplish this.
function isNoIframeOrIframeInMyHost() {
// Validation: it must be loaded as the top page, or if it is loaded in an iframe
// then it must be embedded in my own domain.
// Info: IF top.location.href is not accessible THEN it is embedded in an iframe
// and the domains are different.
var myresult = true;
try {
var tophref = top.location.href;
var tophostname = top.location.hostname.toString();
var myhref = location.href;
if (tophref === myhref) {
myresult = true;
} else if (tophostname !== "www.yourdomain.com") {
myresult = false;
}
} catch (error) {
// error is a permission error that top.location.href is not accessible
// (which means parent domain <> iframe domain)!
myresult = false;
}
return myresult;
}
Best-for-now Legacy Browser Frame Breaking Script
The other solutions did not worked for me. This one works on all browsers:
One way to defend against clickjacking is to include a "frame-breaker" script in each page that should not be framed. The following methodology will prevent a webpage from being framed even in legacy browsers, that do not support the X-Frame-Options-Header.
In the document HEAD element, add the following:
<style id="antiClickjack">body{display:none !important;}</style>
First apply an ID to the style element itself:
<script type="text/javascript">
if (self === top) {
var antiClickjack = document.getElementById("antiClickjack");
antiClickjack.parentNode.removeChild(antiClickjack);
} else {
top.location = self.location;
}
</script>
This way, everything can be in the document HEAD and you only need one method/taglib in your API.
Reference: https://www.codemagi.com/blog/post/194
I actually used to check window.parent and it worked for me, but lately window is a cyclic object and always has a parent key, iframe or no iframe.
As the comments suggest hard comparing with window.parent works. Not sure if this will work if iframe is exactly the same webpage as parent.
window === window.parent;
Since you are asking in the context of a facebook app, you might want to consider detecting this at the server when the initial request is made. Facebook will pass along a bunch of querystring data including the fb_sig_user key if it is called from an iframe.
Since you probably need to check and use this data anyway in your app, use it to determine the the appropriate context to render.
function amiLoadedInIFrame() {
try {
// Introduce a new propery in window.top
window.top.dummyAttribute = true;
// If window.dummyAttribute is there.. then window and window.top are same intances
return !window.dummyAttribute;
} catch(e) {
// Exception will be raised when the top is in different domain
return true;
}
}
Following on what #magnoz was saying, here is a code implementation of his answer.
constructor() {
let windowLen = window.frames.length;
let parentLen = parent.frames.length;
if (windowLen == 0 && parentLen >= 1) {
this.isInIframe = true
console.log('Is in Iframe!')
} else {
console.log('Is in main window!')
}
}
It's an ancient piece of code that I've used a few times:
if (parent.location.href == self.location.href) {
window.location.href = 'https://www.facebook.com/pagename?v=app_1357902468';
}
If you want to know if the user is accessing your app from facebook page tab or canvas check for the Signed Request. If you don't get it, probably the user is not accessing from facebook.
To make sure confirm the signed_request fields structure and fields content.
With the php-sdk you can get the Signed Request like this:
$signed_request = $facebook->getSignedRequest();
You can read more about Signed Request here:
https://developers.facebook.com/docs/reference/php/facebook-getSignedRequest/
and here:
https://developers.facebook.com/docs/reference/login/signed-request/
This ended being the simplest solution for me.
<p id="demofsdfsdfs"></p>
<script>
if(window.self !== window.top) {
//run this code if in an iframe
document.getElementById("demofsdfsdfs").innerHTML = "in frame";
}else{
//run code if not in an iframe
document.getElementById("demofsdfsdfs").innerHTML = "no frame";
}
</script>
if (window.frames.length != parent.frames.length) { page loaded in iframe }
But only if number of iframes differs in your page and page who are loading you in iframe. Make no iframe in your page to have 100% guarantee of result of this code
Write this javascript in each page
if (self == top)
{ window.location = "Home.aspx"; }
Then it will automatically redirects to home page.

window.opener.location not working in IE

I'm trying to redirect from child page to parent page with this javascript:
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "Close", "ClosePopUp();", true);
<script language="javascript" type="text/javascript">
function ClosePopUp() {
window.opener.location= 'ParentPage.aspx';
self.close();
}
</script>
It works with Firefox & Chrome. But not with IE 9.
The error I'm getting is:
Unable to get value of the property 'location': object is null or undefined
alert(window.opener) returns null in IE 9.
After searching for quite a while I have found the solution for internet explorer.
You need to use
window.opener.location.href='';
window.opener is a non-standard property and is not available in all browsers. It will also evaluate to null if the window wasn’t opened from another window, so it seems pretty unreliable.
I think you can use window.open
window.open(URL,name,specs,replace)
More info here
Update
I think I have got it now. Add an eventhandler in your parent window to your child's unload event.
var win = window.open("ChildPage.aspx");
function popUpUnLoaded() {
window.location = "ParentPage.aspx";
}
if (typeof win.attachEvent != "undefined") {
win.attachEvent("onunload", popUpUnLoaded );
} else if (typeof win.addEventListener != "undefined") {
win.addEventListener("unload", popUpUnLoaded, false);
}
This means that when the function below executes your parent page picks up on it.
function ClosePopUp() {
self.close();
}

Getting URL of the top frame

Inside a facebook application I need to check what is the top frame (the main window) URL, and show content accordingly.
I tried using the following:
if (top.location.toString().toLowerCase().indexOf("facebook.com") <0) { ... }
Which works well if the page is not inside an iframe, but when the page is loaded within an iframe (as it does when used as facebook application) the code generates
"Uncaught TypeError: Property
'toString' of object # is not a
function".
Is there any way I can fix this code (with cross-browser compatibility - maybe with jQuery)?
Thanks!
Joel
It is true that cross origin concerns will prevent you from accessing this top window location. However, if you just want the parent window location of the iframe you can get at it via the document.referrer string.
Within your iframe you'd grab the url:
var parentURL = document.referrer
https://developer.mozilla.org/en-US/docs/Web/API/document.referrer
I've used this successfully in my own iframe apps. Also, be aware that if you navigate within your iframe the referrer will change.
Nicholas Zakas has a write-up on his blog:
http://www.nczonline.net/blog/2013/04/16/getting-the-url-of-an-iframes-parent/
The problem you are having that you are not allowed to access top.location across different document domains.
This is a security feature built in to browsers.
Read up on XSS and why the security precautions are in place :)
You can also learn a great deal by reading about the same origin policy
With Martin Jespersen adviced fix, I could check address in iFrame and standart top address:
//this is fix for IE
if (!window.location.origin) {
window.location.origin = window.location.protocol + "//" + window.location.hostname + (window.location.port ? ':' + window.location.port: '');
}
//and here we will get object of address
var urls = (window.location != window.parent.location) ? document.referrer: document.location;
//Martins adviced fix for checking if You are not in iFrame
if (window.top === window) {
urls = urls.origin;
}
//and now indexOf works in both ways - for iFrame and standart top address
if (urls.indexOf("facebook.com") != -1 ) {
//do stuff
}
This could work:
if (self!=top && document.referrer.toLowerCase().indexOf("facebook.com") <0) { ... }
...as long as you don't navigate inside the frame.
But it's not really a good solution ^^
If you need as much information as possible about the top page location:
function getTopLinkInfo() {
var topLinkInfo = {};
try {
// Only for same origins
topLinkInfo.topHref = top.location.href;
}
// Security exception: different origins
catch (error) {
try {
var ancestorOrigins = window.location.ancestorOrigins;
// Firefox doesn't support window.location.ancestorOrigins
if (ancestorOrigins) {
topLinkInfo.parentsDomains = [];
for (var i = 0; i < ancestorOrigins.length; i++) {
topLinkInfo.parentsDomains.unshift(ancestorOrigins[i]);
}
}
// Sometimes referrer refers to the parent URL (but not always,
// e.g. after iframe redirects).
var bottomW = window;
var topW = window.parent;
topLinkInfo.parentsReferrers = [];
// In case of empty referrers
topLinkInfo.parentsHrefs = [];
while (topW !== bottomW) {
topLinkInfo.parentsReferrers.unshift(bottomW.document.referrer);
topLinkInfo.parentsHrefs.unshift(bottomW.location.href);
bottomW = bottomW.parent;
topW = topW.parent;
}
} catch (error) {/* Permission denied to access a cross-origin frame */}
}
return topLinkInfo;
}
var result = getTopLinkInfo();
console.table(result);
console.info(result);

Calling a function inside an iframe from outside the iframe [duplicate]

This question already has answers here:
Invoking JavaScript code in an iframe from the parent page
(17 answers)
Closed 8 years ago.
I have a page with an iframe. Inside that iframe I have a javascript function like this:
function putme() {}
How can I call this function on the main page?
window.frames['frameName'].putme();
Do note that this usually only works if the iframe is referring to a page on the same domain. Browsers restrict access to pages within frames that belong to a different domain for security reasons.
For even more robustness:
function getIframeWindow(iframe_object) {
var doc;
if (iframe_object.contentWindow) {
return iframe_object.contentWindow;
}
if (iframe_object.window) {
return iframe_object.window;
}
if (!doc && iframe_object.contentDocument) {
doc = iframe_object.contentDocument;
}
if (!doc && iframe_object.document) {
doc = iframe_object.document;
}
if (doc && doc.defaultView) {
return doc.defaultView;
}
if (doc && doc.parentWindow) {
return doc.parentWindow;
}
return undefined;
}
and
...
var el = document.getElementById('targetFrame');
var frame_win = getIframeWindow(el);
if (frame_win) {
frame_win.putme();
...
}
...
If the iframe is in a different domain than the outer page, with great difficulty, or not at all.
In general, the browser prevents javascript from accessing code from a different domain, but if you control both pages, there are some hacks to make something work. More or less.
For example, you can change the fragment of the URL of the iFrame from the outer one, poll the fragment from inside the iframe and call that function. There is a similar trick with the name of the window.
On the frameset, specify a name for your frame and in main page you can access the frame by its given name:
window.[FrameName].putme();
You can access the iframe with it's name:
foo.putme();
Functions declared globally inside the iframe page will become members of the window object for that iframe. You can access the window object of the iframe with the iframe's name.
For this to work, your iframe needs to have a name attribute:
<iframe name="foo" ...>
Also, the main page and the iframe page should be from the same domain.
Give the frame a name and an id - both identical.
window.frameNameOrId_.functionName()
Both frames must be in the same domain (though there are ways around this to limited degree)
This can be done with JavaScript:
window.top.location.href = url;
Works perfectly in all major browsers.

Categories

Resources