Detecting Images Within Invisible iFrame? - javascript

I wish to reference this iframe:
<iframe id= "bro" src="http://www.youtube.com" style="visibility:hidden;display:none"></iframe>
Instead of getBackgroundPage() in the following code:
img.src = chrome.extension.getBackgroundPage().imageSrc[0];
I've tried:
img.src = document.getByElementId("bro").imageSrc[0];
That failed hard. Any suggestions?

First of all,
document.getByElementId("bro")
will return an iframe object, and it doesn't have property called imageSrc.
With that, assuming you have the iframe object, you will then have to deal with Cross Domain Policy that will prevent you from accessing the content of 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

Accessing iframe.contentWindow.document not working using postMessage()

My goal is to add css to the iframe content from the parent page. I have two different domains one rendering an iframe from the other, I'm using postMessage to bypass the same-origin policy issue however this doesn't seem to work as expected. When I try to console.log(iframe.contentWindow) I get an error in the console Uncaught DOMException: Blocked a frame with origin "http://parent.domain.com" from accessing a cross-origin frame.
iframe
<iframe
sandbox="allow-same-origin allow-scripts allow-popups allow-forms"
src="https://domain.with.iframe.content"
width="100%"
frameBorder="0"
id="iframe-1"
></iframe>
Page with iframe.
<script>
window.addEventListener('message', function(e) {
var iframe = document.getElementById("iframe-1");
console.log(e)
console.log(e.origin)
console.log(iframe)
console.log(iframe.contentWindow)
}, false);
</script>
Page that I'm iframing.
<script>
var body = document.body
body.onload = function resize() {
parent.postMessage(["hey"], "*");
}
</script>
</script>
From the console I can see that the message event listener is running, however this line console.log(iframe.contentWindow) throws the error. Any help will be much appreciated, thank you.
Adding an answer from my comments:
You can't access iframe.contentWindow from the parent frame, see SecurityError: Blocked a frame with origin from accessing a cross-origin frame
So you'll need to pass the CSS you need back and forth with postMessage.
Depending on how you get the CSS but assuming you have it as a string, you could send that string to the iframe using postMessage. Inside the iframe you could create a style tag, set the innerHTML of that tag to the CSS string and append it to the document head. Like in this article under Global Styles https://dev.to/karataev/set-css-styles-with-javascript-3nl5

JavaScript - trouble accessing DOM of dynamically generated local iframe

I'm having trouble accessing the DOM of an iframe content document if I create the iframe dynamically in JavaScript rather than hard-coding it in the HTML.
I'm finding this so far testing in Mac FF26 and Safari 6. It is a local iframe document on the desktop, so there should be no cross-domain issues.
The iframe I generate appears normally in the browser window. But trying to access it with contentDocument, the body element seems to be empty.
Is this a known issue? Perhaps I'm generating my iframe in an unusual way:
var newIframe = document.createElement("iframe");
newIframe.id = "generatedIframe";
newIframe.src = "test.html";
document.body.appendChild(newIframe);
var iframeTag = document.getElementById("generatedIframe");
// the iframe will be appearing normally in the browser now
// but this fails -- innerHTML is empty string:
var iframeContent = iframeTag.contentDocument.getElementsByTagName("body")[0].innerHTML;
// same reference code works if the iframe is hard-coded in HTML instead
In fact your problem is not the way you generated your iframe.
The iframe DOM is only available after it has been loaded.
The code behind illustrates what I mean :
In your parent window container :
<script>
function doSomething() { alert(iframeTag.contentDocument.getElementsByTagName("body")[0].innerHTML()); }
</script>
In your iframe document
<body onload="window.parent.doSomething();"></body>

Reloading iframe from separate iframe

I have checked all the reload iframe from another iframe posts on stackoverflow...and I have tried all their solutions but it doesn't seem to help me! So my problem is that I have two iframes on the same page. The iframe's sources are php files that interact with each other, however I need the iframes to reload that way the changes are shown. I have tried many different ways (which I will list below). These iframes are from the same domain. Maybe it is something else that is messing this up? Thanks in advance.
Different statements called from inside one iframe:
parent.document.getElementById(id).src = parent.document.getElementById(id).src;
parent.getElementById(id).location.reload();
Trying to call a parent function that works in the parent window:
Inside iframe -
parent.refresh(id);
Parent window working function -
function refresh(id) {
document.getElementById(id).src = document.getElementById(id).src;
}
If you assign name to iframe most browsers will let you access the iframe's window object via the name value. This is different from referring to an iframe by its id property which will give you a reference to the iframe element itself (from its owner document), and not the iframe's content window.
Simple Example: (from the parent document)
<iframe name='iframe1Name' id='iframe1Id'></iframe>
<script>
// option 1: get a reference to the iframe element:
var iframeElem = document.getElementById('iframe1Id');
// update the element's src:
iframeElem.src = "page.html";
// option 2: get a reference to the iframe's window object:
var iframeWindow = window.iframe1Name;
// update the iframe's location:
iframeWindow.location.href = "page.html";
</script>
Let's review your code:
parent.document.getElementById(id).src = parent.document.getElementById(id).src;
This works if executed from within the iframe, provided you use the correct id. You may want to use a debugger to verify that parent.document.getElementById(id) returns a reference to the correct element, and check your console to see if any exceptions are being thrown (try hitting F12). Since you didn't post your full code (including markup) there's no way I can to think of to tell what the issue is here.
Debugging tips:
check parent.location.href to make sure you are accessing the window you think you are,
check parent.document.getElementId(id) to make sure that you get an element object (as opposed to null or undefined),
check parent.document.getElementById(id).tagName to make sure you are using the correct ID (tagName should === "IFRAME")
This line:
parent.getElementById(id).location.reload();
has two problems:
getElementById() is a function of document, but it is being called from parent which is a window object, and
location is a property of a window object. You are trying to access the iframe element's location property, which does not exist. You need a reference to the iframe's window, not its element.
Besides the name method, there are other ways to get the iframe's window object:
document.getElementById('iframeId').contentWindow; // for supported browsers
window.frames["iframeName"]; // assumes name property was set on the iframe
window.frames[i]; // where i is the ordinal for the frame
If changing the src of the iframe element is not working for you, these other fixes might:
parent.document.getElementById(id).contentWindow.location.reload();
or
parent.frames["yourIframeName"].location.reload(); // requires iframe name attribute
or
parent.frames[0].location.reload(); // frames of immediate parent window
or
top.frames[0].location.reload(); // frames of top-most parent window
Caution: If using the name method be careful not to use a common value for name, like "home", for example, as it conflicts with a FireFox function called home() and so Firefox will not automatically create a reference to an iframe's window if it is named home. The most reliable method is probably to use window.frames[] as I believe that has been around for a long time (works in FF / Chrome / Safari / IE6+ (at least))
A more in-depth (but pretty minimal) example follows, tested in Chrome, FF, and IE:
File #1: frametest.html (the parent window)
<!DOCTYPE html>
<html>
<body>
<iframe id="frame1Id" name="frame1Name" src="frame1.html"></iframe>
<iframe id="frame2Id" name="frame2Name" src="frame2.html"></iframe>
</body>
</html>
File #2: frame1.html (frame 1's src)
<!DOCTYPE html>
<html>
<body>
FRAME 1
<script>
document.body.style.backgroundColor="#ccc";
setTimeout(function(){document.body.style.backgroundColor="#fff";},100);
document.write(new Date());
</script>
<input type="button" onclick="parent.document.getElementById('frame2Id').src=parent.document.getElementById('frame2Id').src;" value="Refresh frame 2 by ID"/>
<input type="button" onclick="parent.frame2Name.location.reload();" value="Refresh frame 2 by Name"/>
</body>
</html>
File #3: frame2.html (frame 2's src)
<!DOCTYPE html>
<html>
<body>
FRAME 1
<script>
document.body.style.backgroundColor="#ccc";
setTimeout(function(){document.body.style.backgroundColor="#fff";},100);
document.write(new Date());
</script>
<input type="button" onclick="parent.document.getElementById('frame1Id').src=parent.document.getElementById('frame1Id').src;" value="Refresh frame 2 by ID"/>
<input type="button" onclick="parent.frame1Name.location.reload();" value="Refresh frame 2 by Name"/>
</body>
</html>
This example demonstrates how to define and manipulate iframes by id and by name, and how to affect one iframe from within a different iframe. Depending on browser settings, origin policy may apply, but you already said that your content was all from the same domain so you should be OK there.

Creating iframe by javascript

I have a main page that include a javascript that was creating an iframe dynamically same below:
<script>
document.domain = "mydomain.com"
var iframe = document.createElement("iframe");
document.body.appendChild(iframe);
// creating other element in ifram dynamically
</script>
But in IE I kept receiving a security warning because of document.domain = "mydomain.com" (I need document.domain and I can not remove it).
I found a solution for IE8. this is the solution :
var u = 'javascript:(function(){document.open();document.domain="mydomain.com";document.close();})()';
iframe.src = u;
But it does not work on IE6. Is there any solution for my problem?
Note: I want to create other element in iframe by script and I want to load the content of iframe by src.
Create the iFrame using innerHTML.
Write the full HTML for the iFrame including the SRC attribute. Then find your element and set innerHTML to the string with the iFrame source.

Categories