Write inline javascript in iframe - javascript

I have code that can be reduced to this:
<script>
function write_to_iframe(){
let nw = document.getElementById("mysrc");
let myframe = document.getElementById("myframe");
myframe.contentWindow.document.body.innerHTML = nw.innerHTML;
}
</script>
<iframe id="myframe" width="230" height="95"></iframe>
<div id="mysrc">
<script>
function hello(){
alert("hello world");
}
</script>
SayHello<br>
</div>
It writes the code in the div to the iframe. That part seems to work. However, when I click the SayHello link in the iframe I get a javascript error that the function hello() cannot be found.
What is going wrong here? And how can I declare an inline javascript function in the frame that works.
I am not interested in external javascript files or code that puts everything in the link (like onclick="javascript:alert('hi');").

I would reconsider using an iframe with innerHTML and trying to call a function in the main document from it. The support can vary in different browsers, iframes access to its parent is very limited. If both those things are on the same domain then you don't break CORS policy and you can do more but still there are better options.
If you insist on using iframe, I would consider creating an external path for it (same domain) ex. iframe/embed.html put HTML there normally, then change location after click triggered inside to iframe/embed.html#callHello. And in main document I would add eventListner to detect location change.
const iframe = document.getElementById("iframeId");
window.open("https://example.com/iframe/embed.html", "iframeId");
iframe.addEventListener("load", () => {
if (iframe.contentWindow.location.href.includes('#callHello')) {
hello();
}
});

Related

Open <div> popup outside iFrame

Info: I was working on it for so long, I have a webpage that contains an iframe. Inside that iframe i have opened a page (application) from my own site.
Question: I'm trying to get the <div class = "ps-lightbox"> </ div> inside that iframe out of the iframe. but i cant figure it out with jQuery..
I know it sounds confusing. But I hope you understand my explanation.
Does anyone know how to fix this? You could save my day..
Screenshot of the webpage <
You can not access the elements which are not part of iframe document. But if you have iframe of your own website then window.postMessage can do the trick.
Consider below example:
mainPage.html
<html>
<head>
<script type="text/javascript">
window.addEventListener("message", function(evnet){
if(event.type === "GET_SOME_ELEMENT"){
var iframeWindow = document.getElementsById("iframe1")[0].contentWindow;
iframeWindow.postMessage("POST_SOME_ELEMENT", "TARGET_ORIGIN", {element: $(".some-element")}
}
});
<script/>
</head>
<body>
<div class="some-element"/>
<iframe id="iframe1" src="iframePage.html"/>
</body>
</html>
iframePage.html
<html>
<head>
<script type="text/javascript">
if(window.parent){
window.parent.postMessage("GET_SOME_ELEMENT", "TARGET_ORIGIN");
window.addEventListener("message", function(evnet){
if(event.type === "POST_SOME_ELEMENT"){
console.log(event.data.element);
}
});
}
<script/>
</head>
</html>
The exact question is how to do it with pure JavaScript, not with jQuery.
But I always use the solution that can be found in jQuery's source code. It's just one line of native JavaScript.
For me, it's the best, easily readable and even afaik the shortest way to get the content of the iframe.
First get your iframe
var iframe = document.getElementById('id_description_iframe');
// or
var iframe = document.querySelector('#id_description_iframe');
And then use jQuery's solution
var iframeDocument = iframe.contentDocument || iframe.contentWindow.document;
It works even in the Internet Explorer which does this trick during
the contentWindow property of the iframe object. Most other browsers
use the contentDocument property and that is the reason why we proof
this property first in this OR condition. If it is not set to try
contentWindow.document.
Select elements in iframe
Then you can usually use getElementById() or even querySelectorAll() to select the DOM-Element from the iframeDocument:
if (!iframeDocument) {
throw "iframe couldn't be found in DOM.";
}
var iframeContent = iframeDocument.getElementById('frameBody');
// or
var iframeContent = iframeDocument.querySelectorAll('#frameBody');
Call functions in the iframe
Get just the window element from iframe to call some global functions, variables or whole libraries (e.g. jQuery):
var iframeWindow = iframe.contentWindow;
// you can even call jQuery or other frameworks
// if it is loaded inside the iframe
iframeContent = iframeWindow.jQuery('#frameBody');
// or
iframeContent = iframeWindow.$('#frameBody');
// or even use any other global variable
iframeWindow.myVar = window.myVar;
// or call a global function
var myVar = iframeWindow.myFunction(param1 /*, ... */);
Note
All this is possible if you observe the same-origin policy.
This might help you
var html = $(".ps-lightbox").contents().find("body").html()
And btw, you can get access to iframe's content only from the same origin due to XSS protection
Make sure your code is inside jQuery ready event.
// This won't work
$("#iframe").contents().find('.ps-lightbox');
// This will work
$(function() {
$("#iframe").contents().find('.ps-lightbox');
})

Get all elements inside iframe tag

this is my part of code now i'm using iframe tag and loaded epub on iframe tag
then i don't know how to get all elements inside iframe tag.
jQuery(document).ready(function($) {
var tmp = $('#epub_loader iframe').contents().find('body').html();
alert(tmp);
});
<iframe id="epub_loader" href="test.epub" ></iframe>
`
Assuming both your frames are on the same domain and there is no restriction with Same Domain Policy, you can use the following code from the "parent" frame to get an element in the "child" iframe (in your case body tag).
Pseudo code, you need to actually point to your iframe DOM by id:
var html = document.getElementById('iframe').contentDocument.body.innerHTML;
Notes: In case iframe is on a different domain, you have limited access for browser security reasons.
The thing you need is to wait document will be fully loaded coz you are used iframe,then you should call ....
jQuery(document).ready(function() {
window.onload = function () { //call when iframe is fully loaded
var tmp = $('#epub_loader').contents().find('body').html();
alert(tmp);
};
});

listen even of JavaScript when child popup onload for external link

I want to know that is child popup completely lorded or not?
When i use internal pages of domain like test.html it working but when i am trying with external domain as in my code it not working . so is the any way to achieve this with JavaScript or Jquery.
I am writing code as following.
<script type="text/javascript">
var popup;
function test()
{
popup = window.open("http://dailyhoroscope.com/", "Popup", "width=300,height=100");
popup.onload = function()
{
// Do Somthing
}
};
</script>
If you do not have this onload declaration on the body, add it (or any event which you are trying to create a window with)

javascript proper way to call function

I'm not good in javascript but I find examples and usually understand it. But this is driving me crazy for the last hour. What I'm trying to do is to embed the list.php file to my mainpage.html using the IFRAME. This list.php is showing some links and when I click the link the result should be shown in another place on main page (I'm targeting some div). And those 3 functions are placed inside list.php file.
If I do this:
function autoscroll() {
window.parent.parent.scrollTo(0,0);
}
function resizeIframe(obj) {
obj.style.height = obj.contentWindow.document.body.scrollHeight + 'px';
}
function url2div(url,target){
parent.document.getElementById(target).innerHTML = '<iframe style="width:100%;height:100%;" scrolling="no" frameborder="1" onload="javascript:resizeIframe(this); javascript:autoscroll();" src="' + url + '" />';
}
So if I call the autoscroll() function within my IFRAME like this
onload="javascript:autoscroll();"
autoscroll doesn't work (everything else is working).
But if I put it directly in IFRAME like this:
onload="javascript:window.parent.parent.scrollTo(0,0);"
then it works!
What's wrong with first approach?
It sounds like you're putting the script element in your main page, but then trying to use it in an iframe on the page. Also, you're using window.parent.parent which goes two levels up the containment hierarchy, which seems suspicious.
The iframe and the main window are two different environments. Globals (like your autoscroll) in the main page are not in scope for the iframe's code.
The iframe can access the parent window's globals, provided they're from the same origin, via the parent symbol:
parent.autoscroll();
Then use window, or window.paren, depending on whether you want to scroll the parent or its parent.
It's all about being relative to the document in which the script is included.
Since that was clear as mud: Let's assume your goal is to scroll the main window that the iframe is in:
Option 1: Put it in the iframe (probably best):
In the main window:
Nothing.
In the iframe
<script language="JavaScript">
function autoscroll() {
window.parent.scrollTo(0,0); // <== Only one `parent`, if you want the iframe's parent
}
</script>
and
onload="autoscroll();"
Or:
Option 2: Put it in the main window:
In the main window:
<script language="JavaScript">
function autoscroll() {
window.scrollTo(0,0); // <== No `parent` at all, if you want the main window
}
</script>
In the iframe:
onload="parent.autoscroll();"

call javascript function from outside an iframe

I have one entire html openning inside an iframe that contains a javascript function getData().Now I am not sure how to call getData() from outside that frame.Also is it possible to call it from an external javascript file ?
You can get a reference to the frame window object from the window.frames property. See https://developer.mozilla.org/en/DOM/window.frames
UPDATE:
You can access the global context of a named iframe with window[framename]. e.g:
<iframe src="data.html" name="data"></iframe>
<script>
var myData = window.data.getData();
</script>
Although you will need to make sure the iframe has loaded.
In jQuery you can use the contents method if you want access to the iframe DOM:
$("iframe").contents()
All this is assuming the frame hosted within the same domain.
UPDATE[2]:
You asked if it is possible to call the getData function from an external js file. The answer is yes (if I understand you correctly). Here is an example:
<html>
<head>
<meta charset="utf-8">
<title>parent page</title>
</head>
<body>
<iframe src="data.html" name="data"></iframe>
<script src="getdata.js"></script>
</body>
</html>
Then in the getdata.js file you have:
var dataFrame = window.data;
// when the frame has loaded then call getData()
dataFrame.onload = function () {
var myData = dataFrame.getData();
// do something with myData..
}
Hope this answers your question :)
In certain situation there could be a neccessity of calling a javascript function inside an iframe from the parent document, and vice versa ie;
calling a javascript function in parent document from the iframe.
For example; the parent document have an iframe with id attribute ‘iFrameId‘, and the function ‘functionInIframe()‘ is defined in that iframe document.
Following code can call that iframe function from the parent document itself.
document.getElementById('iFrameId').contentWindow.functionInIframe();
And following code can call the function defined in parent document(functionInParent()) from the iframe itself.
parent.functionInParent();
This way javascript can interact between parent document and iframe.
This is the original post.
in these cases you name your iframe and the main body that uses/launches frame and then use parent.objectname, in JS everything is Object and you should be able to call getData()
a quick googling led me to this -> http://www.esqsoft.com/javascript_examples/iframe_talks_to_parent/

Categories