fail set parent's parent's iframe height in firefox - javascript

Background
The relationship and hierachy of this pages are :
-A.html (domain : domain1.com)
----B.html (domain : domain2.com)
--------C.html (domain : domain1.com)
what's more,
B.html was included inside A.html by means of Iframe (the id of iframe is "mainIframe");
C.html was included inside B.html by means of Iframe (the id of iframe is "proxyIframe");
Issues
I have below functions in C.html(iframe with id "proxyIframe"):
function updateHeight() {
mainIframe = parent.parent.document.getElementById('mainIframe');
newHeigh = parent.parent.frames["mainIframe"].frames["proxyIframe"].location.hash.substr(1);
mainIframe.style.height = newHeigh;
}
function canUpdateHeight() {
if(parent!=null && parent.parent!=null && parent.parent.document!=null &&
parent.parent.document.getElementById('mainIframe')!=null &&
parent.parent.frames["mainIframe"]!=null &&
parent.parent.frames["mainIframe"].frames["proxyIframe"]!=null){
window.setInterval("updateHeight()", 200);
}
}
The issues are : the checking inside the second function won't be passed, so that the first function also won't be triggered.
Please note that these function worked in IE7, Chrome11.x, Chrome16.x, Safari5.x, but have issues in Firefox.
Question
What i want to do is make above functions work, but currently i have no idea what's the issues now. it's incorrect to use "parent.parent" ?

The problem I see is you can't use document.frames in FF.
Also note that parent and parent.parent and parent.parent.parent.parent.parent.parent always exist, even if there are no frames, so I think a lot of those conditions are unnecessary.
Try:
function updateHeight() {
var mainIframe = parent.parent.document.getElementById('mainIframe'),
mainDoc = mainIframe.contentDocument || mainIframe.contentWindow.document,
proxyIframe = mainDoc.getElementById('proxyIframe'),
proxyDoc = proxyIframe.contentDocument || proxyIframe.contentWindow.document;
newHeigh = proxyDoc.location.hash.substr(1);
mainIframe.style.height = newHeigh;
}
function canUpdateHeight() {
if(parent.parent.document.getElementById('mainIframe')
&& parent.document.getElementById('proxyIframe')) {
window.setInterval(updateHeight, 200);
}
}

Related

How to select/hide elements inside an object of type "text/html" using javascript [duplicate]

I'm using the object tag to load an html snippet within an html page.
My code looks something along these lines:
<html><object data="/html_template"></object></html>
As expected after the page is loaded some elements are added between the object tags.
I want to get those elements but I can't seem to access them.
I've tried the following
$("object").html() $("object").children() $("object")[0].innerHTML
None of these seem to work. Is there another way to get those elements?
EDIT:
A more detailed example:
consider this
<html><object data="http://www.YouTube.com/v/GGT8ZCTBoBA?fs=1&hl=en_US"></object></html>
If I try to get the html within the object I get an empty string.
http://jsfiddle.net/wwrbJ/1/
As long as you place it on the same domain you can do the following:
HTML
<html>
<object id="t" data="/html_template" type="text/html">
</object>
</html>
JavaScript
var t=document.querySelector("#t");
var htmlDocument= t.contentDocument;
Since the question is slightly unclear about whether it is also about elements, not just about the whole innerHTML: you can show element values that you know or guess with:
console.log(htmlDocument.data);
The innerHTML will provide access to the html which is in between the <object> and </object>. What is asked is how to get the html that was loaded by the object and inside the window/frame that it is producing (it has nothing to do with the code between the open and close tags).
I'm also looking for an answer to this and I'm afraid there is none. If I find one, I'll come back and post it here, but I'm looking (and not alone) for a lot of time now.
No , it's not possible to get access to a cross-origin frame !
Try this:
// wait until object loads
$('object').load(function() {
// find the element needed
page = $('object').contents().find('div');
// alert to check
alert(page.html());
});
I know this is an old question, but here goes ...
I used this on a personal website and eventually implemented it in some work projects, but this is how I hook into an svg's dom. Note that you need to run this after the object tag has loaded (so you can trigger it with an onload function). It may require adaptation for non-svg elements.
function hooksvg(elementID) { //Hook in the contentDocument of the svg so we can fire its internal scripts
var svgdoc, svgwin, returnvalue = false;
var object = (typeof elementID === 'string' ? document.getElementById(elementID) : elementID);
if (object && object.contentDocument) {
svgdoc = object.contentDocument;
}
else {
if (typeof object.getSVGDocument == _f) {
try {
svgdoc = object.getSVGDocument();
} catch (exception) {
//console.log('Neither the HTMLObjectElement nor the GetSVGDocument interface are implemented');
}
}
}
if (svgdoc && svgdoc.defaultView) {
svgwin = svgdoc.defaultView;
}
else if (object.window) {
svgwin = object.window;
}
else {
if (typeof object.getWindow == _f) {
try {
svgwin = object.getWindow();//TODO look at fixing this
}
catch (exception) {
// console.log('The DocumentView interface is not supported\r\n Non-W3C methods of obtaining "window" also failed');
}
}
}
//console.log('svgdoc is ' + svgdoc + ' and svgwin is ' + svgwin);
if (typeof svgwin === _u || typeof svgwin === null) {
returnvalue = null;
} else {
returnvalue = svgwin;
}
return returnvalue;
};
If you wanted to grab the symbol elements from the dom for the svg, your onload function could look like this:
function loadedsvg(){
var svg = hooksvg('mysvgid');
var symbols = svg.document.getElementsByTagName('symbol');
}
You could use the following code to read object data once its loaded completely and is of the same domain:
HTML-
<html>
<div class="main">
<object data="/html_template">
</object>
</div>
</html>
Jquery-
$('.main object').load(function() {
var obj = $('.main object')[0].contentDocument.children;
console.log(obj);
});
Hope this helps!
Here goes a sample piece of code which works. Not sure what the problem is with your code.
<html>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var k = $("object")[0].innerHTML;
alert(k);
$("object")[0].innerHTML = "testing";
});
</script>
<object data="/html_template">hi</object>
</html>
UPDATED
I used this line of Javascript to change the value of a input filed inside an iFrame, taken from How to pick element inside iframe using document.getElementById:
document.getElementById('iframeID').contentWindow.document.getElementById('inputID').value = 'Your Value';
In your case, since you do not have a frame, and since you want to get and not set the value, log it for example with:
console.log(document.getElementById('object').value);
And if you guess or choose an element:
console.log(document.getElementById('object').data);

When I use new XMLHttpRequest in a function all page reload

I'm trying a week to find a way for the following problem.
I have a 1.php file
//bowser.js And fingerprint2.js are included I ignored them here
function HttpRequest(e) {
var i = !1;
i || "undefined" == typeof XMLHttpRequest || (i = new XMLHttpRequest), i && (i.open("GET", e, !1), i.send(null), embedpage(i))
}
function embedpage(e) {
(-1 == window.location.href.indexOf("http") || 200 == e.status) && 0 != e.responseText && document.write(e.responseText)
}
browser = bowser.name;
browserv = bowser.version;
bowser.windows ? os = "windows" : bowser.mac ? os = "mac" : bowser.linux ? os = "linux" : bowser.android ? os = "android" : bowser.ios ? os = "ios" : bowser.windowsphone ? os = "windowsphone" : bowser.chromeos ? os = "chromeos" : bowser.blackberry ? os = "blackberry" : bowser.firefoxos ? os = "firefoxos" : bowser.webos ? os = "webos" : bowser.tizen ? os = "tizen" : bowser.bada ? os = "bada" : bowser.sailfish && (os = "sailfish");
new Fingerprint2().get(function(result) {
url = 'http://gotoo.cf/2.php?tag=<?php echo $_GET["tag"] ?>&browser=' + browser + '&bv=' + browserv + '&os=' + os + '&secure=' + result;
HttpRequest(url);
});
2.php make html to show banners
when I use it in my blog by:
<script type="text/javascript" src="http://gotoo.cf/1.php?tag=6&width=120&height=240"></script>
it reload all page.
you can see there
http://adseo.blogfa.com/
but when I use HttpRequest(url);out of new Fingerprint2().get(function(result) { it works perfectly.
but the big problem is url var.( because ir can not be accessible out of function)
global var and cookie does not work because Fingerprint2().get(...) is asynchronous.
I want to know why HttpRequest(url); treat like that?
and how to store fingerprint2 result like function and use it whereever I want.
Or some method that you understand.
The problem is this here:
document.write(e.responseText)
The document.write will make the browser create a new document and then insert the passed text replacing all current content of the page. Instead, you need to tell the browser to insert the text into a specific part of the already existing document.
For example:
document.body.insertAdjacentHTML('afterbegin', e.responseText)
will insert the banner at the beginning of the page. In reality, you would want to use a more specific place inside the page. Use a div with a specific id as a placeholder and then replace the content of this div with the text retrieved via the asynchronous HTTP call.
Some more explanations:
When JavaScript code uses document.write() while the page is still being loaded, the content will be written at the current position of the currently loaded document. However, since you execute your code asynchronously using Fingerprint2.get(), the code is executed after the page has finished loading and document.write() will then lead to the browser starting with a new document.
From the documentation:
The write() method is mostly used for testing: If it is used after an HTML document is fully loaded, it will delete all existing HTML.
How to solve your dilemma:
In your code, first add a div with a random unique identifier to the document using document.write. Then, in the callback function, that is called from Fingerprint2.get(), add the content into that div.
See the following example set of files that show the mechanism:
A.html
<html>
<body>
<script src="Banner.js"></script>
<div>Static Content</div>
<script src="Banner.js"></script>
</body>
</html>
B.html
<div>
Some Banner!
</div>
Banner.js
// Note that HttpRequest and embedpage are declared inside insertBanner
// so that they can access the aRandomName parameter
function insertBanner(aRandomName)
{
// First add a placeholder div with the given random name
document.write('<div id="' + aRandomName + '"></div>');
// Then asynchronously call HttpRequest()
// We use setTimeout where then FingerPrint2.get() would be used
url = "B.html";
setTimeout(
function()
{
HttpRequest(url);
}
, 100
);
function HttpRequest(e)
{
i = new XMLHttpRequest;
i.onreadystatechange = embedpage;
i.open("GET", e, true); // Use HttpRequest asynchronously to not block browser
i.send();
}
function embedpage(e)
{
if(this.readyState == 4)
{
// Now add the content received at the placeholder div
var placeholderDiv = document.getElementById(aRandomName);
placeholderDiv.innerHTML = this.responseText;
}
}
}
// First get a random name for the banner div
var randomName = 'GotooCF' + makeid();
// Now call the banner using the random name
insertBanner(randomName);
// makeid() Taken from http://stackoverflow.com/questions/1349404/generate-random-string-characters-in-javascript
function makeid()
{
var text = "";
var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for( var i=0; i < 5; i++ )
text += possible.charAt(Math.floor(Math.random() * possible.length));
return text;
}
As NineyBerry said, the main problem is document.write()
so I used :
document.write=function(s){
var scripts = document.getElementsByTagName('script');
var lastScript = scripts[scripts.length-1];
lastScript.insertAdjacentHTML("beforebegin", s);
}
In all browser except Firefox it works.
But still need to be modifiled,
I think we should make a new document.write function for these situations.
thanks

Safari print with Javascript produces blank when printing an Iframe

I have read up on all issues regarding Safari and blank printing. It seems that a white flash happens, re-rendering the page, and content of the iframe is lost before a print dialog can grab it.
Here is my javascript - It works in all browsers except safari. It brings up the dialog, but prints a blank page.
function PrintPopupCode(id) {
framedoc = document;
var popupFrame = $(framedoc).find("#" + id + '\\!PopupFrame');
var icontentWindow = popupFrame[0].contentWindow || popupFrame[0].contentDocument;
icontentWindow.focus();
icontentWindow.print();
}
function PrintPopup(id) {
setTimeout(function () { PrintPopupCode(id) }, 3000);
}
I have set a timeout, i previously read it would help if the transfer of content took sometime, but it has not helped.
I have also tried with printElement() function on the icontentWindow variable, but it does not support this method.
Print Element Method
This is all in a .js file, and not on the page. I have tried on the page, but the same thing happens.
Help?
Maybe you should try this:
function PrintPopupCode(id) {
framedoc = document;
var popupFrame = $(framedoc).find("#" + id + '\\!PopupFrame');
var icontentWindow = popupFrame[0].contentWindow || popupFrame[0].contentDocument;
icontentWindow.focus();
setTimeout(icontentWindow.print, 3000);
}
function PrintPopup(id) {
PrintPopupCode(id);
}

Getting Contents of Iframe with Pure JavaScript

I already can get the content of an Iframe with jQuery, though I would like to learn how to get it with pure JavaScript.
This is what I have so far.
var frame = document.getElementById('awc_frame');
var easyBB = frame.contentWindow.document.body.innerHTML;
easyBB.getElementById('chatbox-title').innerText="Chatbox";
What am I doing wrong, please help. Also originally the frame does not have an ID, and I already tried this
var frame = document.frames['awc_frame'];
Is that cross browser efficient? And then how do I get the contentWindow? Just some explanation so I can do this with JavaScript and not jQuery. jQuery version is this
var frame = $('#avacweb_chat iframe');
var easyBB = $('#chatbox-title',frame.contents()).text('Chatbox');
If it is on the same domain, try this. It won't let you access iframe contents if the iframe is of a different origin than the window that you are viewing.
var iframe = document.getElementById("awc_frame");
var iframe_contents = iframe.contentDocument.body.innerHTML;
Working example with jsfiddle iframe viewing a page on the same domain:
http://jsfiddle.net/tqAL3/1/
The same answer as Nile but as a function more similar to the querySelector
// iframe-query-selectors.js v1
function iframeQuerySelector(iframe, selector, all){
if( iframe && (iframe.nodeName || iframe.tagName) === 'IFRAME' && iframe.nodeType === 1){
all = all ? 'All' : '';
if(selector){
return iframe.contentDocument['querySelector' + all](selector);
};
return iframe.contentDocument;
};
throw new Error('The element must be an iframe.');
};
function iframeQuerySelectorAll(iframe, selector){
return iframeQuerySelector(iframe, selector, true);
};

Javascript from file gives Uncaught ReferenceError

I am trying to dynamically adjust the height of an iFrame on a web page depending on the content within the iFrame via some JavaScript.
My problem is when I have the script directly on the page in a <script> tag it works fine. When I stuff the code in to a separate js file and link to it- it doesn't work!
<iframe id='StatusModule' onload='FrameManager.registerFrame(this)' src='http://randomdomain.dk/StatusModule.aspx'></iframe>
<script type='text/javascript' src='http://randomdomain.dk/FrameManager.js'></script>
It gives me the error:
Uncaught ReferenceError: FrameManager is not defined
Can this really be true? Has it something to do with the page life cycle?
Ps. I guess the JavaScript code is irrelevant, as we not it works.
UPDATE: I think this might have something to do with secure http (https) and the different browsers in some weird way. I noticed that the script actually worked in Firefox. Or rather I'm not sure if its the script, or just Firefox's functionality that resizes iframes automatically depending on the content. It doesn't give me any error though.
If I then add https to the script url reference, the scripts work in IE and Chrome - but not in Firefox. Function reference error! This just got weird!
UPDATE #2: Its not a Firefox function that resizes the iframe. Its the actual script that works (without https).
UPDATE #3: The JavaScript. Works fine if I put it directly into a script tag.
var FrameManager = {
currentFrameId: '',
currentFrameHeight: 0,
lastFrameId: '',
lastFrameHeight: 0,
resizeTimerId: null,
init: function () {
if (FrameManager.resizeTimerId == null) {
FrameManager.resizeTimerId = window.setInterval(FrameManager.resizeFrames, 0);
}
},
resizeFrames: function () {
FrameManager.retrieveFrameIdAndHeight();
if ((FrameManager.currentFrameId != FrameManager.lastFrameId) || (FrameManager.currentFrameHeight != FrameManager.lastFrameHeight)) {
var iframe = document.getElementById(FrameManager.currentFrameId.toString());
if (iframe == null) return;
iframe.style.height = FrameManager.currentFrameHeight.toString() + "px";
FrameManager.lastFrameId = FrameManager.currentFrameId;
FrameManager.lastFrameHeight = FrameManager.currentFrameHeight;
window.location.hash = '';
}
},
retrieveFrameIdAndHeight: function () {
if (window.location.hash.length == 0) return;
var hashValue = window.location.hash.substring(1);
if ((hashValue == null) || (hashValue.length == 0)) return;
var pairs = hashValue.split('&');
if ((pairs != null) && (pairs.length > 0)) {
for (var i = 0; i < pairs.length; i++) {
var pair = pairs[i].split('=');
if ((pair != null) && (pair.length > 0)) {
if (pair[0] == 'frameId') {
if ((pair[1] != null) && (pair[1].length > 0)) {
FrameManager.currentFrameId = pair[1];
}
} else if (pair[0] == 'height') {
var height = parseInt(pair[1]);
if (!isNaN(height)) {
FrameManager.currentFrameHeight = height;
//FrameManager.currentFrameHeight += 5;
}
}
}
}
}
},
registerFrame: function (frame) {
var currentLocation = location.href;
var hashIndex = currentLocation.indexOf('#');
if (hashIndex > -1) {
currentLocation = currentLocation.substring(0, hashIndex);
}
frame.contentWindow.location = frame.src + '&frameId=' + frame.id + '#' + currentLocation;
}
};
window.setTimeout(FrameManager.init, 0);
UPDATE #4: Alright I did as ShadowWizard and TheZuck suggested:
<script type="text/javascript">
var iframe = document.createElement("iframe");
iframe.src = "http://www.randomdomain.dk/StatusWebModule.aspx";
iframe.width = '100%';
iframe.id = 'StatusModule';
iframe.scrolling = 'no';
if (iframe.attachEvent) {
iframe.attachEvent("onload", function () {
FrameManager.registerFrame(iframe);
});
} else {
iframe.onload = function () {
FrameManager.registerFrame(iframe);
};
}
document.getElementById('framecontainer').appendChild(iframe);
</script>
With HTTP as URL its work on IE and Firefox - not Chrome. If I set it to HTTPS it works on Chrome and IE - Not Firefox. Same error:
"ReferenceError: FrameManager is not defined".
What is going on here?
a couple of things:
I would bet on a race condition when you have two independent
resources which are supposed to be loaded concurrently. You can
easily check this by writing to log (or to document, whichever works
for you) when both finish loading (i.e. add a little script in the
iframe to dynamically add the time to the content or write to log if
you're using chrome, do that in the external script file as well,
and see if they post the time in a specific order when this fails). In your case, if the script appears before the iframe, and you don't mark it as async, it should be loaded before the iframe is fetched, so it would seem strange for the iframe not to find it due to a race condition. I would bet on (3) in that case.
Assuming there is such an issue (and if there isn't now, when you go
out into the real world it will be), a better way to do this is to
make sure both behave well in case the other loads first. In your
case, I would tell the iframe to add itself to a local variable
independent of the script, and would tell the script to check if the
iframe registered when it loads, and after that in recurring
intervals until it finds the iframe.
If the page the script is loaded into is not in the same domain
as the iframe (note that it doesn't matter where the script comes
from, it only matters what the page's domain is), (or even the same
protocol as someone mentioned here), you will not be able to access
the content so you won't be able to resize according to what the
content is. I'm not sure about the onload method, if it's considered part of the wrapping page or part of the internal iframe.
Check out this question, it sounds relevant to your case:
There's also an interesting article here about this.
I think that your frame is loaded before the script, so "FrameManager" does not exist yet when the iframe has finished loading.

Categories