Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing a variable in JavaScript to open.window

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...

like image 896
Parshuram Kalvikatte Avatar asked Jan 26 '26 05:01

Parshuram Kalvikatte


1 Answers

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);
like image 158
lin Avatar answered Jan 28 '26 18:01

lin