Use JavaScript variable as iframe src? - javascript

I'm trying to use a JavaScript variable as the src in a <iframe>, the user will then be able to load other content by choosing scr in a menu, which changes the variable. the default src URL is apps/start.php.
Here some code from my index.php:
<script>
var appurl = "start.php";
document.getElementById("app").src = "apps/" + appurl();
</script>
<iframe id="app" src="">
</iframe>
The problem is that i can't get this first small part working... The <script> tag is in the <head>. And when the src is changing will the new document automatically load?

Wait for the page to load (note that this is only going to work when the iframe is on your domain)
window.onload = function(){
var appurl = "start.php";
document.getElementById("app").src = "apps/" + appurl;
};

The problem is that the Javascript is run before the iframe is there. Put your javascript below your iFrame or inside the document ready and it will work.
Example document onload:
<script>
window.onload = function ()
{
var appurl = "start.php";
document.getElementById("app").src = "apps/" + appurl();
}
</script>
<iframe id="app" src="">
</iframe>

<script>
window.onload = function ()
{
var appurl = "start.php";
document.getElementById("app").src = "apps/" + appurl;
}
</script>
<iframe id="app" src="">
</iframe>

Try
<script>
window.onload = function(){
var appurl = 'start.php';
document.getElementById("app").src = "apps/" + appurl;
};
</script>

Related

Get iframe content by using JavaScript

I have a HTML file named test.html and below are the content of that file.
<html>
<head></head>
<body>
This is the content.
</body>
</html>
Now I have another file where I want to show the test.html content by iframe and then match the content with something and do something if it matches.
Here is what I'm trying but I'm not getting the iframe data.
<html>
<head></head>
<body>
<iframe id="myIframe" src="test.html"></iframe>
<script>
var iframe = document.getElementById("myIframe");
var iframe_content = iframe.contentDocument.body.innerHTML;
var content = iframe_content;
// var content = "This is the content."; --> I want to get the iframe data here like this. Then match it with the following.
var find = content.match(/ is /);
if (find) {
document.write("Match Found");
} else {
document.write("No Match!");
}
</script>
</body>
</html>
Thanks in advance
As stated in the comments, you need to wait for the iframe content to load. https://developer.mozilla.org/en-US/docs/Web/Events/load
<iframe id="myIframe" src="https://stackoverflow.com/questions/45525117/get-iframe-content-by-using-javascript#"></iframe>
<script>
const myFrame = document.getElementById('myIframe');
myFrame.addEventListener('load', (evt) => {
console.log(evt.target === myFrame);
console.log(evt.target);
});
</script>
Nothing will work unless your web page and iframe have the same origin

Access DOM from iFrame

I have inserted a HTML page into an iframe:
<iframe src="file:///C:/editor.html" width="1000" height="500" frameborder="0"></iframe>
Now I need to access to the DOM from the iframe and get an element by id.
This is my editor.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Diagram</title>
<script type="text/javascript" src="lib/jquery-1.8.1.js"></script>
<!-- I use many resources -->
<script>
function generatePNG (oViewer) {
var oImageOptions = {
includeDecoratorLayers: false,
replaceImageURL: true
};
var d = new Date();
var h = d.getHours();
var m = d.getMinutes();
var s = d.getSeconds();
var sFileName = "diagram" + h.toString() + m.toString() + s.toString() + ".png";
var sResultBlob = oViewer.generateImageBlob(function(sBlob) {
b = 64;
var reader = new window.FileReader();
reader.readAsDataURL(sBlob);
reader.onloadend = function() {
base64data = reader.result;
var image = document.createElement('img');
image.setAttribute("id", "GraphImage");
image.src = base64data;
document.body.appendChild(image);
}
}, "image/png", oImageOptions);
return sResult;
}
</script>
</head>
<body >
<div id="diagramContainer"></div>
</body>
</html>
I need to access the DOM from the iframe, and get image.src from my edtior.html. How can I do this?
Use window.parent or window.top to access the parent/primary frame window. Then you can get their elements with
window.parent.document.getElementById("id")
and so on.
So you can have in iframe.html:
<html><body>
<script>
var getDiv = function(){
return window.parent.document.getElementById("test");
}
</script>
</body></html>
And a page containing it:
<html><body>
<div id="test"></div>
<iframe src="#####/iframe.html"></iframe>
</html></body>
Now calling getDiv() inside the iframe will fetch you the div[id=test] inside the parent frame.
If you want to do the opposite, i.e. access an element inside an iframe from outside the iframe, please read this answer:
Javascript - Get element from within an iFrame

insert dynamically string containing script into HTML and executing it dynamically

I have a variable of the form :
var x = '<script type="text/javascript" language="javascript"> ..lots of stuff...</script>
<script type="text/javascript" language="javascript"> ..even more of stuff...</script>'
and I want to insert it with jquery into my HTML code and execute it.
I tried using the append, html and eval without any luck.
Any ideas?
sample script:
<script type="text/javascript" language="javascript">
var clk = 'http://......';
</script>
<script type="text/javascript" language="javascript" src="http://...."></script>
<noscript>
<img src="http://..." width="120" height="600" border="0" alt="">
</noscript>
this will in the end show an img, which will load asynchronously.
Usually having </script> tags nested within other <script></script> tags will break things. You'll need to split them up like in the Javascript below to not cause browser issues.
Here is a working fiddle:
https://jsfiddle.net/2vrfxrse/
Javascript
var jsCode = '<scr' + 'ipt>var executeTest = function(){ alert("This is a test."); }</scr' + 'ipt>';
$('head').append(jsCode);
HTML
<script>executeTest();</script>
This solution will probably work for your specific scenario:
var rx = new RegExp("<script .*?>(.*?)<\/script>", 'g');
var x = '<script type="text/javascript" language="javascript">alert("..lots of stuff...");</script><script type="text/javascript" language="javascript">alert("..even more of stuff...");</script>';
var res = rx.exec(x);
while (res) {
var s = document.createElement("script");
s.appendChild(document.createTextNode(res[1]));
document.body.appendChild(s);
res = rx.exec(x);
}
JSBin: http://jsbin.com/menocumiya/edit?html,js,console,output
You can use Jquery getScript:
//Moment example
if (typeof moment == "undefined") {
var url = "~/assets/js/moment.js";
$.getScript(url);
}
Or Jquery Function:
$(function(){
var test = "this.Foo = function() {alert('hi');}";
var F=new Function (test);
(new F()).Foo(); //Shows "Hi" alert
});
$(function(){
var test = "this.Foo = function() {alert('hi');}";
var F=new Function (test);
(new F()).Foo(); //Shows "Hi" alert
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

JavaScript output to url

I need to output a DIV width into a URL for an iframe but am having some trouble. I have managed to get java to output the div width, but encounter a problem when getting this into the URL. Below is the code I am using (notice the width=
<iframe src="http://www.coveritlive.com/index2.php/option=com_altcaster/task=viewaltcast/altcast_code=3f43697a78/height=670/width=<script language='javascript'>var e = document.getElementById('Single2');
document.write(e.offsetWidth);</script>"></iframe>
This outputs the URL as:
http://www.coveritlive.com/index2.php/option=com_altcaster/task=viewaltcast/altcast_code=3f43697a78/height=670/width=var e = document.getElementById('Single2');
document.write(e.offsetWidth);
As you can see the URL has the full javascript in, not just it's output.
Ideally the URL should be as such (lets assume the DIV width is 650px).
http://www.coveritlive.com/index2.php/option=com_altcaster/task=viewaltcast/altcast_code=3f43697a78/height=670/width=650
Any ideas how I can get this working?
You should do this in the following way (pseudo code)
<iframe id="myIframe"></iframe>
<script>
document.getElementById("myIframe").src = ... // construct URL here
</script>
Let me know if you need a working example.
Here is a working example
<head>
<script type="text/javascript">
function changeContent()
{
console.log("changing src");
var myIframe = document.getElementById("guy");
myIframe.src = "http://steps.mograbi.info/users/sign_in?unauthenticated=true&width=" + myIframe.offsetWidth;
}
</script>
</head>
<body>
<iframe id="guy"></iframe>
<script>
document.onload = changeContent();
</script>
</body>
If you track the network, you will see the width passing..
You can't put <script> tag in src, it will be treated as String.
<iframe id="myiframe"></iframe>
<script type='text/javascript'>
var e = document.getElementById('Single2');
var url = "http://www.coveritlive.com/index2.php/option=com_altcaster/task=viewaltcast/altcast_code=3f43697a78/height=670/width=" + e.offsetWidth;
document.getElementById("myiframe").setAttribute("src",url);
</script>

call function on iframe mouse move

I have a function that i need to call on iframe mousemove(). But i didnt found anything like we have in body tag
We have <body mousemove="Function()"> Do we have anything like this for iframe??
The iframe contains its own document, own body element etc.
Try something like this:
var frame = document.getElementById("yourIframeId");
// IE is special
var frameDoc = frame.contentDocument || frame.contentWindow.document;
var frameBody = frameDoc.getElementsByTagName("body")[0];
var testingOneTwo = function() {
console.log("Hello, is this thing on?");
};
frameBody.onmouseover = testingOneTwo;
Did you mean onMouseOver or onFocus?
e.g.
<HTML>
<HEAD>
<TITLE> New Document </TITLE>
<script language="javascript">
<!--
function SayHello()
{
alert("Hi from IFrame");
}
//-->
</script>
</HEAD>
<BODY>
<iframe id="myiFrame" onMouseOver="SayHello()"/>
<iframe id="myiFrame" onFocus="SayHello()"/>
</BODY>
</HTML>

Categories