Getting Contents of Iframe with Pure JavaScript - 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);
};

Related

Search content inside iframe using indexOf

Basicly im trying to find certain text inside iframe, i get no errors in console, i have no clue what im doing wrong in here. Im trying to use indexOf because if Im not searching inside iframe it works good. I tried to addapt using this post here -> How to get the body's content of an iframe in Javascript? but keeps not working. Can someone give me and hand?
setTimeout(function() {
var iframe = document.getElementById('aspxcontent');
var iframeDocument = iframe.contentDocument || iframe.contentWindow.document;
var iframeContent = iframeDocument.getElementById('DialogMainBody');
[].slice.call(document.querySelectorAll('pre'), 0).forEach(function(aEl) {
if (aEl[iframeContent].indexOf('update') > -1) {
console.log("found");
}else{
console.log("not found");
}
});
}, 5000);
edit 1
var x = document.getElementsByTagName("iframe")[0].contentWindow;
//x = window.frames[0];
x.document.getElementsByTagName("body")[0].style.backgroundColor = "blue";
// this would turn the 1st iframe in document blue.

HTML/JavaScript: How to copy text from a iframe

I'm kinda new to web development. I'm trying to copy text from a iframe into a textarea on a Bootstrap-html webpage.
An example of my code is here: https://jsfiddle.net/fe5ahoyw/
JavaScript
I have tried:
var a = document.getElementById('LD1');
var b = document.getElementById('OD1');
if (a != null)
{
b.value = a.value;
}
I have also tried:
var a = document.getElementById('LD1').innerHTML;
var a = document.getElementById('LD1').value;
var a = document.getElementById('LD1').html;
Any help would be any help would be much appreciated
Frostie
The JSFiddle is currently trying to access a http resource. As JSFiddle itself is https, most browsers will not like this very much.
That said, the selectors you are using inside the code are ... off. You need to get the frame itself -> content of the frame -> element within the frame you are interested in. I'd suggest using something like:
var a = document.getElementById('OD1');
var iFrame = document.getElementById('LD1');
var iFrameDocument = iFrame.contentDocument || iFrame.contentWindow.document;
content = iFrameDocument.body.textContent;
alert(content);
if (content)
{
a.value = content.value;
}

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.

Trouble with iFrame.contentDocument

Basically, im making a javascript to refresh a page and it will find the price and buy the item when it goes up for the price desired.
I got it to work without the iframe, but I need to to work in the iframe, which is the problem ive reached.
If you went to this page: [ http://m.roblox.com/items/100933289/privatesales ]
and ran this code:
alert(document.getElementsByClassName('currency-robux')[0].innerHTML);
You would get an alert for the lowest price. In the code, this doesnt work (Hence, my problem.)
Try running the code below on this page to get it to work [ http://www.roblox.com/Junk-Bot-item?id=100933289 ]
var filePath = document.URL;
var itemid = filePath.slice(((filePath.search("="))+1));
var mobileRoot = 'http://m.roblox.com/items/';
var mobileEnd = '/privatesales';
var mobileFilePath = mobileRoot+itemid+mobileEnd;
var iframe2 = '<iframe id="frame" width="100%" height="1" scrolling="yes"></iframe>';
document.write(iframe2);
var iframe = parent.document.getElementById("frame");
iframe.height = 300;
iframe.width = 500;
iframe.src = mobileFilePath;
var price;
var snipe = false;
var lp = Number(prompt("Snipe Price?"));
document.title = "Sniping";
function takeOutCommas(s){
var str = s;
while ((str.indexOf(",")) !== -1){
str = str.replace(",","");
}
return str;
}
function load() {
if (snipe == false) {
tgs = iframe.contentDocument.getElementsByClassName('currency-robux');
price = Number((takeOutCommas(tgs[0].innerHTML)));
alert(price);
}
}
iframe.onload = load;
You might try having both pages — the one from "m.roblox.com" and the one from "www.roblox.com" — add the following up at the top of the head:
<script>
document.domain = "roblox.com";
</script>
Code from the different domains won't be allowed to look at each others page contents, but if you set the domains to the same suffix then it should work.
If you can't get it to work by sharing the same document.domain="roblox.com" code then you can try posting messages to the iframe.
Put this inside the iframe page:
window.addEventListener('message',function(e) {
});
In the parent page execute this to pass a message (can be a string or object, anything really) to the iframe:
document.getElementById("frame").contentWindow.postMessage({ "json_example": true }, "*");
Put this in the parent to listen for the message:
window.addEventListener("message", messageReceived, false);
function messageReceived(e) {
}
From inside the iframe posting a message back out:
window.parent.postMessage('Hello Parent Page','*');

Load URL from text box into iframe

How do you load a URL from a text box into iframe in a HTML file via javascript?
var oIFrame = document.getElementById("id_of_iframe");
oIFrame.src = document.getElementById("id_of_textbox").value;
Or with document.frames if its the only iframe you are using:
var myIframe = window.document.frames[0]; // lets grab the iframe object
if (myIframe != null){
myIframe.src = document.getElementById("id_of_textbox").value; // set the value as source.
}
Just to add I guess, via jQuery
$('iframe#guid').src( $('#textbox_id').val() );
with error checking:
var iframe = $('#guid');
if(iframe.length > 0){
iframe.attr('src', $('#textbox_id').val());
}

Categories