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.
Related
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.
I have variable which is i think global ,,so all my child functions must be able to get that variable,But i am getting a reference error,Variable not declared
Here is below code.Please help if i am doing any wrong thing.Thanku
<!DOCTYPE html>
<html>
<head>
<script>
var Test1Object = 'Testing'; // This is my variable
</script>
<script src = 'ch.js'>
</script>
</head>
<body>
<button onclick="openwindow()">Create window</button>
</body>
</html>
My Ch.js
(function(){
alert(Test1Object) // Here i am getting this object
this.openwindow = function() {
w =window.open("untitled.html",'TheNewpop','height=315,width=625');
w.document.write(
"<body>"+
"<\/body>" +
"<script src = \"windowpo.js\"><\/script>" // THis is where i reference my windowpo.js
)
w.document.close();
w.focus();
}
})()
My windowpo.js
(function(){
alert(Test1Object) // Here there is not Test1Object (Reference error)
})();
My issue is that in my windowp.js how can i get my Test1Object Variable...
Easy doing by just acessing your refrence inside the window by using window.opener like in this runnable demo plnkr. Inside your window application you can access it via window.opener.Test1Object where window.opener holds a reference of the JavaScript instance where it was opened. In that way you can access all the stuff you configured in your main application:
Source: window.opener MDN reference
View
<!DOCTYPE html>
<html ng-app="myApp">
<head lang="en">
<meta charset="utf-8" />
<title>Custom Plunker</title>
<script type="text/javascript">
var Test1Object = 'Testing';
</script>
<script src="main.js"></script>
</head>
<body>
<a onclick="openwindow()">Open Window</a>
</body>
</html>
main.js
this.openwindow = function() {
w = window.open(location.href+"untitled.html",'TheNewpop','height=315,width=625');
w.document.close();
w.focus();
}
unitiled.html
Some Test
<script src="windowpo.js"></script>
windowpo.js
alert(window.opener.Test1Object);
As most other answers don't seem to even read the question properly, I'll add my 2 cents as an answer, too:
The main problem in your code, is that you have to JS execution contexts here: One for the original page (the HTML code you show) and one for the popup you open in Ch.js. In general both do not share any data, variables or whatever.
You have, however, a window object reference in your variable w after calling window.open(). You use this already to inject HTML code to the popup.
If you now want to have JS variables available in the popup JS context, you can either inject additional <script> tags into the popups HTML code and set the variables there (bad choice, imho) or use postMessage() to send data across. I give some sample code for the postMessage() variant below:
Ch.js
this.openwindow = function() {
w = window.open("untitled.html",'TheNewpop','height=315,width=625');
w.document.write(
"<body>"+
"<\/body>" +
"<script src = \"windowpo.js\"><\/script>" // THis is where i reference my windowpo.js
);
w.document.close();
w.focus();
// wait for pupup to be ready
window.addEventListener( 'message', function( e ){
// send the variable
if( e.data == 'inited' ) {
w.postMessage( Test1Object, '*' );
}
})
}
windowpo.js
// wait for messages from opener
window.addEventListener( 'message', function( e ) {
alert( e.data );
});
// tell the opener we are waiting
window.opener.postMessage( 'inited', '*' );
For some more information see the respective MDN article on Window.postMessage().
You need to declare the variable before you include in any file. Simply create a script tag above the included files define it there.
<script type='text/javascript' >
var Test1Object = 'Testing';
</script>
<script type='text/javascript' src='js/Ch.js'></script>
<script type='text/javascript' src='js/windowpo.js'></script>
this way you should be able to use withing all files
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;
}
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;
Using the Soundcloud JavaScript API, I want to dynamically generate a page of player widgets using track search results. My code is as follows:
<html>
<head>
<script src="http://connect.soundcloud.com/sdk.js"></script>
<script>
function makeDivsFromTracks(tracks,SC)
{
var track;
var permUrl;
var newDiv;
for(var ctr=0;ctr<tracks.length;ctr++)
{
newDiv=document.createElement("div");
newDiv.id="track"+ctr;
track=tracks[ctr];
SC.oEmbed(track.permalink_url,{color:"ff0066"},newDiv);
document.body.appendChild(newDiv);
}
}
</script>
</head>
<body>
<script>
SC.initialize({
client_id: 'MY_CLIENT_ID'
});
SC.get('/tracks',{duration:{to:900000},tags:'hitech',downloadable:true},
function(tracks,SC)
{
makeDivsFromTracks(tracks,SC);
});
</script>
</body>
</html>
When I load this, the SC.oEmbed() call throws an error:
Uncaught TypeError: Cannot call method 'oEmbed' of null
which would seem to indicate that either the divs aren't being generated or the search results aren't being returned, but if I remove the SC.oEmbed() call and replace it with:
newDiv.innerHTML=track.permalink_url;
then I get a nice list of the URLs for my search results.
And if I create a widget using a static div and static URL, e.g.
<body>
<div id="putTheWidgetHere"></div>
<script>
SC.initialize({
client_id: 'MY_CLIENT_ID'
});
SC.oEmbed("http://soundcloud.com/exampleTrack", {color: "ff0066"}, document.getElementById("putTheWidgetHere"));
</script>
</body>
then that works fine as well. So what's the problem with my oEmbed() call with these dynamically created elements?
Solved it. I took out the SC argument from the callback function and makeDivsFromTracks(), and now all the players show up. Not sure exactly why this works--maybe it has to do with the SC object being defined in the SDK script reference, so it's globally available and doesn't need to be passed into functions?
Anyways, working code is:
<html>
<head>
<script src="http://connect.soundcloud.com/sdk.js"></script>
<script>
function makeDivsFromTracks(tracks)
{
var track;
var permUrl;
var newDiv;
for(var ctr=0;ctr<tracks.length;ctr++)
{
newDiv=document.createElement("div");
newDiv.id="track"+ctr;
track=tracks[ctr];
//newDiv.innerHTML=track.permalink_url;
SC.oEmbed(track.permalink_url,{color:"ff0066"},newDiv);
document.body.appendChild(newDiv);
}
}
</script>
</head>
<body>
<script>
SC.initialize({
client_id: 'MY_CLIENT_ID'
});
SC.get('/tracks',{duration:{from:180000,to:900000},tags:'hitech',downloadable:true},function
(tracks){makeDivsFromTracks(tracks);});
</script>
</body>
</html>