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
Related
This question already has answers here:
What is the purpose of the var keyword and when should I use it (or omit it)?
(19 answers)
Closed 4 years ago.
If I try to declare s as a variable it errors out. It is acting like s isn't a variable and really doesn't like any changes to the syntax at all.
I've actually written a decision tree webpage that relies on this concept a lot and I'm not sure why it works.
<!DOCTYPE html>
<html>
<head>
<title>Class Tests</title>
<meta http-equiv="X-UA-Compatible" content="IE=edge" charset="UTF-8"/>
<script src=" jQuery3.2.1.js"></script>
<script src=" jQuery_UI.js"></script>
</head>
<script>
function selection(select){
s = select;
}
$(document).ready(function(){
$("button").click(function(){
alert("boop " + s);
});
});
</script>
<body>
<button onclick=selection('Genius')>Genius</button>
<button onclick=selection('System')>Systems</button>
<button onclick=selection('Personal')>Personal</button>
</body>
</html>
A variable is undeclared when it does not use the var keyword. It gets created on the global object (that is, the window), thus it operates in a different space as the declared variables.
Find out more on this link
Variables that are assigned without var keyword are called undeclared. These are created in the global scope. So your s variable is available in the click handler.
Now this only happens in non-strict mode, so if you put 'use strict' directive inside or above the selection function you'll get an error.
<!DOCTYPE html>
<html>
<head>
<title>Class Tests</title>
<meta http-equiv="X-UA-Compatible" content="IE=edge" charset="UTF-8"/>
<script src=" jQuery3.2.1.js"></script>
<script src=" jQuery_UI.js"></script>
</head>
<script>
'use strict'
function selection(select){
s = select;
}
$(document).ready(function(){
$("button").click(function(){
alert("boop " + s);
});
});
</script>
<body>
<button onclick=selection('Genius')>Genius</button>
<button onclick=selection('System')>Systems</button>
<button onclick=selection('Personal')>Personal</button>
</body>
</html>
Setting your s like this:
function selection(select){
s = select;
}
is similar (for variable scope) to:
var s;
function selection(select) {
s = select;
}
So s exists as a property of window, and available both inside of selection function and for alert("boop " + s);, because window is a global object. But if you declare and assign a value to variable with var inside a function:
function selection(select) {
var s = select;
}
s will have only a scope of function selection, and retrieving it here:
alert("boop " + s);
causes an error, because it doesn't exist here.
im having 2 html files, in my first file i have declared a variable and i want to use the same variable in my second file...
my first file code is
<script type="text/javascript">
function topics(clicked_id)
{
var ids = clicked_id;
var myObject, fol;
myObject = new ActiveXObject("Scripting.FileSystemObject");
if(!myObject.FolderExists("D:/JavaScript/Work/Days/"+ids))
{
fol = myObject.CreateFolder("D:/JavaScript/Work/Days/"+ids);
}
load_page();
}
function load_page()
{
open("file:///D:/JavaScript/Work/Topics_Page.html");
}
</script>
i want to use "ids" variable in my second file...
Thanks;
If the HTML documents have the same origin you can use postMessage, MessageChannel, SharedWorker or storage event to communicate between different browsing contexts, see
How can I load a shared web worker with a user-script?
Can we refer to JavaScript variables across webpages in a browser session?
how to pass data from one html page to second in php?
You can use localStorage and storage event to use the same object variable, or define a local variable set to the value of localStorage at a different HTML documenta having the same domain.
<!DOCTYPE html>
<html>
<head>
<title>index</title>
</head>
<body>
otherPage.html
<h1>set id</h1>
<script>
let id;
let h1 = document.querySelector("h1");
h1.onclick = e => {
id = `${Math.E * Math.PI * Math.random()}`;
localStorage.setItem("id", id);
console.log(`id: ${id} at ${e.type}`);
}
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<title>other page</title>
<script>
let id = localStorage.getItem("id");
console.log(`id: ${id} at ${document.title}`);
onstorage = e => {
console.log(`id: ${localStorage.getItem("id")} at ${e.type}`);
id = localStorage.getItem("id");
console.log(id);
}
</script>
</head>
<body>
<h1>otherPage.html</h1>
</body>
</html>
plnkr https://plnkr.co/edit/m4RIdwgIl74Dk6YmGAgI?p=preview
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.
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;
I have a bunch of web pages where I have an identical construct:
<html>
<head>
<script src="sorttable.js"></script>
<noscript>
<meta http-equiv="refresh" content="60">
</noscript>
<script type="text/javascript">
<!--
var sURL = unescape(window.location.pathname);
function doLoad()
{
setTimeout( "parent.frames['header_frame'].document.submitform.submit()", 60*1000 );
}
function refresh()
{
window.location.href = sURL;
}
//-->
</script>
<script type="text/javascript">
<!--
function refresh()
{
window.location.replace( sURL );
}
//-->
</script>
<script type="text/javascript">
<!--
function refresh()
{
window.location.reload( true );
}
//-->
</script>
</head>
<body>
.
.
.
<script type="text/javascript">
window.onload = function() { sorttable.innerSortFunction.apply(document.getElementById("OpenFace-2"), []); doLoad(); }
</script>
</body>
</html>
This works perfectly in every page except for one, where when the onload function runs it cannot find the sorttable code (which is loaded from sorttable.js up at the top). All these pages are part of the same application and are all in the same dir along with the js file. I do no get any errors in the apache log or the js console until that page loads, when I get:
sorttable.innerSortFunction is undefined
I can't see what makes this one page different. Can anyone see what is wrong here, or give me some pointers on how I can debug this further?
The code I pasted in is from the source of the page where it does not work, but it is identical as the pages where it does work.
Looks like on that page the table with id OpenPhace-2 by which you try to sort have no needed class: sortable
The function innerSortFunction of sorttable object will be present only if there is any table with sortable class exists.