How to execute javascript code on IFrame load - javascript

I am dynamically creating an iframe with javascript inside the body.
iframe = m_oYDOM.get("ifAdwords");
iframe.contentWindow.document.body.innerHTML = <script type=\"text/javascript\">function Test(){alert(\"Success\");Test();}</script>";
I am not able to get the alert to work. Can someone help me!

I got this working
iframe = document.getElementByID("iFrameID");
var oDoc = iframe.contentWindow.document;
oDoc.open();
oDoc.write('<html><body><script type=\"text/javascript\">function Test(){alert(\"success\");}Test();<\/script><\/body><\/html>');
oDoc.close();

.innerHTML is only for text changes... Call the script from another *.html file. OR just add onload to the end of iframe like so:
<iframe src="test.html" onload="alert('Success')";>

Heres an example using jQuery that I use to execute javascript when a frame has loaded, I use it when redirecting the user to download a zip file, to control the browser after the download dialog appears.
Add a div to the page that will hold the iframe:
<div style='height: 1px; width: 1px; border: 0;' id='iframediv'></div>
Then call the following to create the iframe with the onload action:
var url = "http://google.com"
$('#iframediv').html('<IFRAME id="downloadAlbum" onload="loadFunction()" src="'+url+'"></iframe>');
Change url and loadFunction as required.

Related

Write inline javascript in iframe

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();
}
});

Load iframe or div inside js after ajax complete

On my site ajax calling iframe that is loading some sort of data. I want to load the iframe or div data as soon as the ajax request completes or data is loaded. I cannot access ajax directly, so I am trying it this way, but it is showing undefined. I think this is due to the iframe or div not loading each time. Any help with how I can load the iframe or div inside js without touching ajax code.Thanks
<script type="text/javascript">
setTimeout(function() { alert(jQuery('#wrapper').html()); }, 10000);
</script>
If I use pplus instead of wrapper its only show empty iframe. But I want to load its data.
Iframe code looks like this :
<div id="ppplus" style="height: 535px;"><iframe allowtransparency="true" style="height: 535px; width: 870px; border: none;">
<html>
<div class="content" id="wrapper">data goes here</div>
</html>
</iframe></div>
i dont know why you want to use i frame just to display data ..
use a div. iframes behave different than divs. you dont have innerHTML. you have a body (myFrame.contentDocument.body)
dont use a timer you dont know when the response will be rendered.
add a eventlistener like DOMSubtreeModified or DOMNodeInserted for the wrapper div and get its content
var ppplus = document.getElementById('ppplus');
ppplus.addEventListener("DOMSubtreeModified",function(e) {
var myFrame = e.target.firstchild;
console.log(myFrame.contentDocument.body);
});

Using JS how to change HTML tag attributes (alternative to document.write() )

I am using an outside API that allows me to send extra parameters inside the image src value, like so
<img src="myImage.jpg?resize=width[scrW]">
The problem is that I don't know what the width variable(scrW) is until I start loading the page. I use <script> var scrW = window.innerHtml </script> to get the width I need.
I tried using
<script>
document.write('<img src="myImage.jpg?resize=width['+window.innerHtml+']">')
</script>
but the problem with that is that document.write displays everything in text until the document is ready (or reaches </body>). And that just looks tacky.
My question is: How can I append/prepend JS variables to src attribut values during the page rendering?
How about just solving the problem of the text showing up before the page renders? That's easy. Just make sure your code doesn't run until the page's HTML is completely loaded.
Vanilla JS solution:
<script>
// self executing function here
(function() {
// your page initialization code here
// the DOM will be available here
document.write('<img src="myImage.jpg?resize=width['+window.innerHtml+']">');
})();
</script>
Using jQuery:
<script>
$(document).ready(function() {
document.write('<img src="myImage.jpg?resize=width['+window.innerHtml+']">');
});
</script>
How about you give your image src some default resize value and when the page is loaded it will be updated. I have given the img an id of "myImage" so that I can access that in JavaScript code.
Here is the HTML:
<img id="myImage" src="myImage.jpg?resize=width[180]">
Insert this JavaScript at the end:
<script>var scrW = window.innerHTML;
document.getElementById("myImage").src = "myImage.jpg?resize=width["+scrW+"]";</script>

Loader div is not hiding onload function for dynamic generated iframe src

I am using this code to generate and download PDF file.
Here is the sample code,
<div id="ajax_loading"></div>
function print_profile(pid,vid)
{
$("#ajax_loading").show();
var type=$("input[name=share_to]:checked").val();
var perpage=$("input[name=perpage]:checked").val();
var url=storeurl+"/ajax/ajax-action.php?type="+type+"&vid="+vid+"&playlist_id="+pid+"&perpage="+perpage+"&action=get_profile";
var iframe = document.getElementById("download-container");
iframe.src = url;
}
And i have iframe in footer like this,
<iframe id="download-container" style="visibility: hidden; width: 0px; height: 0px;" onload="document.getElementById('ajax_loading').style.display='none';"></iframe>
Here, when print_profile function will call, it create dynamic URL and set it in iframe. So iframe loads that url and download that file. What i am trying to do is, When iframe generating PDF, need to show loading div. so for that i added this function in iframe,
onload="document.getElementById('ajax_loading').style.display='none';"
But its not working for me. id there any solution for this? Am i doing anything wrong here?
Here is jsfiddle which is working for content URL fiddle but its not working with my URL. i think it because my URL is generating output?

MathJax not working with iFrame

I am trying to call MathJax Function on iFrame by click event. Here is the code
html
<body onLoad="ifon();">
<iframe name="richTextField" id="richTextField" style="border:#000000 1px solid; width:700px; height:300px;"></iframe>
<button onclick="refresh();"></button>
</body>
javascript
function ifon(){
richTextField.document.designMode = 'On';
}
function refresh(){
var richTextField = document.getElementById("richTextField");
if(richTextField != null) {
var get_iframe_text = richTextField.contentWindow.document.body.innerHTML;
if(get_iframe_text.slice(-6) == "$$<br>"){
//Trying to call MathJax on iFrame
MathJax.Hub.Queue(["Typeset",MathJax.Hub,richTextField]);
alert("Success");
}
}
}
The refresh() nested if condition will executed only if the last six character are $$<br>
Can any one help me how to call MathJax.Hub.Queue([]) on iFrame ?
You can not use MathJax from outside the iframe to process math within the iframe. You need to load MathJax inside the iframe itself. You can still trigger MathJax from outside if you need to by calling the MathJax that is inside the iframe, provided that the contents is from the same domain as the container. Otherwise, you would need to set up an event listener and use postMessage to communicate with the iframe.
At last I found a solution for this problem. Just replacing iFrame with HTML5 ContentEditale Div.
Now it is working Fine...

Categories