Is it possible to access a array that is outside an iframe? - javascript

The problem is this: inside my main page (parent.html) I have an iframe (child.html) and a script block. In that script block there is a array of integers and a function that adds elements to the list. In the iframe there is a new function that adds an element to the list of the main file (parent.html).
I would like to know if it is possible for the iframe (child.html) to access this function found in parent.html. Example:
parent.html
<html>
<head>
<title>Parent</title>
<script>
var parentList = [0];
var counter = 0;
function addValue(){
counter++;
parentList.push(counter);
console.log('parent', parentList);
}
</script>
</head>
<body>
<button onclick="addValue()">Add Value (Parent)</button>
<br />
<iframe src="child.html" allowfullscreen></iframe>
</body>
</html>
child.html
<html>
<head>
<title>Child</title>
</head>
<body>
<button onclick="addValueInternal()">Add Value Child</button>
<script>
var internalCount = 0;
function addValueInternal() {
internalCount++;
parentList.push(internalCount);
console.log('child', parentList);
}
</script>
</body>
</html>
The error:
child.html:12 Uncaught ReferenceError: parentList is not defined
at addValueInternal (child.html:12)
at HTMLButtonElement.onclick (child.html:6)

Yes. it is possible. Based on an example calling a function defined in the parent from an embedded iframe.
So in your case, you would have to reference the parent when accessing your array.
function addValueInternal() {
internalCount++;
parent.parentList.push(internalCount); // here we access the reference
console.log('child', parentList);
}
Be aware that you may encounter problems concerning the cross-origin policy afterwards.

Related

How to insert variable into <img> src parameter?

I am trying to generate QR code on my webpage with a data (id) I get from web service. I can not figure out how to insert a javascript variable as a part of <img> src parameter.
As you can see I can change the src using myFunction (AFTER button clicked). But I do not know how to insert id variable to the initial page load (to replace ID1_GOES_HERE at the end of img line).
Please help!
Here is a code:
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<title>TEST</title>
</head>
<body>
<script>
var id1 = "41c0236f-ed21-4182-be3d-26513078f704";
function myFunction(){
var id2 = "41c0236f-ed21-4182-be3d-26513078f704";
document.getElementById('qr_img').src="http://chart.apis.google.com/chart?cht=qr&chs=300x300&chld=H|0&chl="+id2;
}
</script>
<img id="qr_img" src="http://chart.apis.google.com/chart?cht=qr&chs=300x300&chld=H|0&chl=ID1_GOES_HERE"/>
<button onclick="myFunction()">test</button>
</body>
</html>
Don't use a button click handler, just call the function from your script:
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<title>TEST</title>
</head>
<body>
<script>
var id1 = "41c0236f-ed21-4182-be3d-26513078f704";
function myFunction(){
var id2 = "41c0236f-ed21-4182-be3d-26513078f704";
document.getElementById('qr_img').src = document.getElementById('qr_img').src + id2;
}
myFunction();
</script>
<img id="qr_img" src="http://chart.apis.google.com/chart?cht=qr&chs=300x300&chld=H|0&chl="/>
<button>test</button>
</body>
</html>
The click handler is used to capture the button click event, and do something at that time. That's not what you want, so remove the button click handler.
At the end of the <script> element, simply call myFunction() to do what it's intended for.
If you wanted to run the script after the entire document and all of its dependencies were loaded, you could do this:
<script>
var id1 = "41c0236f-ed21-4182-be3d-26513078f704";
function myFunction(){
var id2 = "41c0236f-ed21-4182-be3d-26513078f704";
document.getElementById('qr_img').src = document.getElementById('qr_img').src + id2;
}
document.onload = myFunction();
</script>
For this simple case, you probably don't actually need a function at all, and the body of myFunction can simply be placed inline, like so:
<script>
var id1 = "41c0236f-ed21-4182-be3d-26513078f704";
var id2 = "41c0236f-ed21-4182-be3d-26513078f704";
document.getElementById('qr_img').src = document.getElementById('qr_img').src + id2;
</script>
The function would be useful if you had more logic involved, and needed to organize (or modularize) it.
You could add this to your script below where you declared and set the id1 variable
function Window_OnLoad ()
{
document.getElementById("qr_img").src="http://chart.apis.google.com/chart?cht=qr&chs=300x300&chld=H|0&chl="+id1;
}

js function not changing value

I have the following code. The first time the function is called the iframe changes contents to newPage but the second time the function is called the page doesn't change.
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Submit</title>
<script>
var url = 1;
function setURL(url){
var win1 = "http://localhost/Audio/src/submit1.html" ;
var win2 = "http://localhost/Audio/src/newPage.html";
if (url === 1){
document.getElementById('iframe').src=win2;
url=2;
}
else{
document.getElementById('iframe').src=win1;
url=1;
}
}
</script>
</head>
<body>
<iframe src="http://localhost/Audio/src/audio.html" style="width:0;height:0;border:0; border:none;"></iframe>
<iframe id="iframe" style="border:0; " src="http://localhost/Audio/src/submit1.html">
</iframe>
<input type="button" value="click me 71" onclick="setURL(url)">
</body>
</html>
You have two variables called url.
The one defined as a global and the one defined as the function argument.
Your function only changes the one defined as the function argument, which isn't preserved anywhere.
If you want to modify the global one: Don't define the argument in the function definition (and don't bother passing an argument to the function).
since you are passing the same name as parameter (url) you have to explicitly say which one do you want to change or change the parameter name (from url to u for instance)

Pass a Javascript Object to an HTML iframe (as an Object)

A MainWindow creates a JavaScript object that the ChildWindow needs to utilize utilize.
My MainWindow.html looks like this at the moment
<html>
<body>
<script>
var varObject = {type:"Error", message:"Lots"};
</script>
<iframe class="child" src="ChildWindow.html"></iframe>
</body>
</html>
The ChildWindow.html looks like this
<html>
<body>
<script>
console.log(varObject.type); // goal is to log "Error"
</script>
</body>
</html>
The ChildWindow is trying to use the object that was created in the MainWindow which of course it can't because I don't yet know how to pass it.
I've tried to Google this but most of the solutions I found involved passing the values as strings instead of as a variable.
One can simply pass the object by assigning the object to the window of the iframe.
in the parent window:
var frame = document.querySelector("iframe");
frame.contentWindow.object_of_interest = object_of_interest;
in the iframe'ed window
console.log(window.object_of_interest);
Please have a look at following code :
<html>
<body>
<script>
var varObject = {type:"Error", message:"Lots"};
var child = document.getElementsByClassName("child")[0];
var childWindow = child.contentWindow;
childWindow.postMessage(JSON.stringify(varObject),*);
</script>
<iframe class="child" src="ChildWindow.html"></iframe>
</body>
</html>
In ChildWindow.html
<html>
<body>
<script>
function getData(e){
let data = JSON.parse(e.data);
console.log(data);
}
if(window.addEventListener){
window.addEventListener("message", getData, false);
} else {
window.attachEvent("onmessage", getData);
}
</script>
</body>
</html>
Hope it helps :)
You should use window.postMessage to send messages to and from iFrames embedded in your site.

Issue with getElementById

I have written the following code to display an input with Javascript's alert( ... ) function.
My aim is to take a URL as input and open it in a new window. I concatenate it with 'http://' and then execute window.open().
However, I just get 'http://' in the URL name, even after concatenation, and not the complete URL. How can I fix this?
<html>
<head>
<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
<meta content="utf-8" http-equiv="encoding">
<body onload="onload();">
<input type="text" name="enter" value="" id="url_id">
<input type="button" value="Submit" onclick="func();">
</body>
<script type="text/javascript">
var url;
function onload() {
url = document.getElementById("url_id").value;
}
function func(){
var var1 = "http://";
var var2 = url;
var res = var1.concat(var2);
alert(var2);
//window.open(res);
}
</script>
</head>
</html>
You shouldn't be calling it in onload(), only after the user has entered the url into the input field. Of course its an empty string, because you assign url to the value of #url_id before the user has a chance to enter anything when you place it in onload().
function func(){
var var1 = "http://";
url = document.getElementById("url_id").value;
var var2 = url;
var res = var1.concat(var2);
alert(var2);
//window.open(res);
}
Others have given solutions, and you already have accepted one. But none of them have told you what is wrong with your code.
Fristly, you have a body element inside your head element. This is invalid markup. Please correct it:
<html>
<head>
<!-- this is a script -->
<script type="text/javascript">
// javascript code
</script>
</head>
<body>
<!-- this is an inline script -->
<script type="text/javascript">
// javascript code
</script>
</body>
</html>
Secondly, you need to have an idea about the execution order of JavaScript inside browser windows. Consider this example:
<html>
<body onload="alert('onload')">
<p>Lorem Ipsum</p>
<script type="text/javascript" >
alert('inline');
</script>
</body>
</html>
Which alert do you thing will get executed first? See the JSFiddle.
So as you can see, inline JavaScript will be executed first, and then the browser will call whatever code is in <body onload=.
Also, onload function is called immediately after the page is loaded. And user has not entered anything when the function is executed. That is why you get null for url.
function func()
var url = document.getElementById("url_id").value;
var fullUrl = "http://".concat(url);
alert(fullUrl);
// or window.open(fullUrl);
}
You're not concatenating with a String but with an Object. Specifically an HTMLInputElement object.
If you want the url from the text input, you need to concatenate with url.value.
if its not concatenating, use:
var res = val1+val2.value;

Object #<HTMLDocument> has no method 'getElementByName'

I copy some javascript example form jsfiddle and run them on local server but it shows the error on google chrome at inspect_element/console. Any suggestions for fixing this? Thanks.
error:
Uncaught TypeError: Object #<HTMLDocument> has no method 'getElementByName'
compute onclick
my code:
<!DOCTYPE html>
<html>
<head>
<title>My fruit</title>
<script type="text/javascript">
function checkFruit(){
var fruit_radio_pointers = document.getElementsByName("fruit");
var which_fruit = null;
for(var i=0; i<fruit_radio_pointers.length; i++){
if(fruit_radio_pointers[i].checked){
which_fruit = fruit_radio_pointers[i].value;
break;
}
}
alert(which_fruit);
}
document.getElementById("my_btn").addEventListener("click", checkFruit, false);
</script>
</head>
<body>
<p>
<button id="my_btn">Which Fruit?</button>
</p>
</body>
</html>
Names do not enforce uniqueness in html, so the function is getElementsByName (note the s after Element). When you change this, remember it will return an array, not one element.

Categories

Resources