0

Currently I have data table which has child rows as well , In child rows one of my column having the href link and I have the following onClick event to it.

File1.js

var empObj = {'name' : "Abc"};
var cell = row.insertCell(-1);
var hrefLink = document.createElement('a');
hrefLink.setAttribute('href',"#");
hrefLink.setAttribute('id',"all");        
hrefLink.setAttribute('onClick',"window.open('/App/home/happyPath', '_blank', 'toolbar=yes,scrollbars=yes,resizable=yes,top=300,left=60,width=1100,height=650')");
hrefLink.innerHTML = "ALL";
cell.appendChild(hrefLink);
cell.style.textAlign = "center";
row.appendChild(cell);

In above code snippet its creating the href element and aim getting in the child rows and Also on click its opening new window with target html.

But its open the new window I'm laoding File2.js from thymleaf script tag <script th:src="@{/resources/build/js/File2.js(v=${startUpTime})}" />

Now here in File2.js I wanted to use the variable empObj from the File1.js for other data manipulation and computation.

Can anyone please help on this.

MainPage.html

<html>
<head>
<!-- <link rel="stylesheet" media="all"
    th:href="@{/vendors/jquery/jquery.dataTables.min.css(v=${startUpTime})}" />

</head>
<body>

  <div id="container"> 

This page will load the datable which having child rows with href link, code for loading the dataTable is implemented in the File1.js in dodcument ready method. </div>

  <th layout:fragment="page-specific-js" th:remove="tag">
  <script th:src="@{/resources/build/js/File1.js(v=${startUpTime})}" />
  </th>
</body>
</html>

NewWindow.html

  <html>
    <head>
    <!-- <link rel="stylesheet" media="all"
        th:href="@{/vendors/jquery/jquery.dataTables.min.css(v=${startUpTime})}" />

    </head>
    <body>

      <div id="container"> 

    This page has to load the data form File2.js , But for this  I reuiqred the object which is there in File1.js.  , And If I declare File1.js in thus page then it will load DataTable of mainPage.html which actually not required. </div>

      <th layout:fragment="page-specific-js" th:remove="tag">
   <script th:src="@{/resources/build/js/File2.js(v=${startUpTime})}" /> 
      </th>
    </body>
    </html>
Tanveer
  • 97
  • 1
  • 16

5 Answers5

1

It looks like some additional code context may be missing and that this might actually be in a loop or otherwise not contained within the global namespace. In the literal code provided, empObj would be accessible by File2 if it is loaded on the page after File1.

Guessing that you're not loading File1 and File2 on the same page or have empObj contained within the scope of a function. Either way, some alternatives:

  • Use something like WebPack or Browserify to simplify scope and make your code more modular (plus lots more benefits)
  • Store your data using the Web Storage API in File1 and access them in File2
  • Pass the key/value pairs to the new window via query string (IE: /App/home/happyPath?name=Abc) and parse them in File2
Community
  • 1
  • 1
Kevin Reilly
  • 6,096
  • 2
  • 25
  • 18
  • I'm not loading the file1 and file 2 on same page , I'm already webapck and browserify . for passing as query string in `hrefLink.setAttribute('onClick',"window.open('/App/home/happyPath', '_blank', 'toolbar=yes,scrollbars=yes,resizable=yes,top=300,left=60,width=1100,height=650')");` how I can add object and pass as query param. – Tanveer Apr 05 '17 at 06:28
  • You can [convert](http://stackoverflow.com/questions/1714786/query-string-encoding-of-a-javascript-object) an object to a query string and just append it the URL (first parameter of window.open) and then [parse](http://stackoverflow.com/questions/2090551/parse-query-string-in-javascript) the query string in File2. Added these links to the answer as well. – Kevin Reilly Apr 05 '17 at 07:01
  • I tried using exactly what you said , but after appending the param which is serialised `var empObj = {'name' : "Abc"}; var params = serialize(empObj);` I'm getting error as **SyntaxError: Invalid character '\u8204'**. at line `hrefLink.setAttribute('onClick',"window.open('/App/home/happ‌​yPath'?'+params, '_blank', 'toolbar=yes,scrollbars=yes,resizable=yes,top=300,left=60,wi‌​dth=1100,height=650'‌​)");`. Even I printed the logs I got as expected (log >> Params are – "name=Abc"). – Tanveer Apr 05 '17 at 08:01
  • Looks like you need to remove the single quote from before the question mark: `'/App/home/happ‌​‌​yPath'?'+params` >> `'/App/home/happ‌​‌​yPath?'+params`. Are you replacing "Abc" with some other real text that has a specific character encoding? – Kevin Reilly Apr 05 '17 at 08:10
  • Ah sorry, I think you also meant to use double quotes. `"window.open('/datamonitorda‌​shboard/home/allReco‌​rdsForPart?'+param, '_blank', 'toolbar=yes,scrollbars=yes,resizable=yes,top=300,left=60,wi‌​‌​dth=1100,height=65‌​0'‌​)"` >> `"window.open('/datamonitorda‌​shboard/home/allReco‌​rdsForPart?" + param +"', '_blank', 'toolbar=yes,scrollbars=yes,resizable=yes,top=300,left=60,wi‌​‌​dth=1100,height=65‌​0'‌​)"` – Kevin Reilly Apr 05 '17 at 08:40
  • Finally got it... It was taking some special char in the URL ... so I was getting that error,, No i'm able append the param ....Thanks lot :) Now how I can access those params in File2.js ? – Tanveer Apr 05 '17 at 10:12
  • Parse them: http://stackoverflow.com/questions/2090551/parse-query-string-in-javascript – Kevin Reilly Apr 05 '17 at 10:28
  • Done , These steps worked for me, Thanks :), where I struck is I was getting special chars in the URL which I dint noticed .... – Tanveer Apr 05 '17 at 12:30
1

Serialize empobj and use as query string to pass to another page and from another page you can again get that query string values from url and unserialize it there. Below is an answer of your question that how you can serialize empobj and pass to another page and use there.

Code in File1.js

serialize = function (obj) {
  var str = [];
  for (var p in obj) if (obj.hasOwnProperty(p)) {
     str.push(encodeURIComponent(p) + '=' +     encodeURIComponent(obj[p]));
   }
  return str.join('&');
  }
 var empObj = {
    'name': 'Abc'
 };
 var param = serialize(empObj);
 var href = '/App/home/happ‌yPath?' + param;
 var cell = row.insertCell(-1);
 var hrefLink = document.createElement('a');
 hrefLink.setAttribute('href',"#");
 hrefLink.setAttribute('id',"all");        
 hrefLink.setAttribute('onClick', 'window.open(\'' + href + '\', \'_blank\', \'toolbar=yes,scrollbars=yes,resizable=yes,top=300,left=60,w‌​idth=1100,height=650‌​\')');
 hrefLink.innerHTML = "ALL";
 cell.appendChild(hrefLink);
 cell.style.textAlign = "center";
 row.appendChild(cell);

now how to use value of query string from url on another page js.

code in File2.js

var queryString = window.location.search;
queryString = queryString.replace('?', '');
var empObj = {};
var pairs = queryString.split('&');
for (i in pairs) {
 var split = pairs[i].split('=');
 empObj[decodeURIComponent(split[0])] = decodeURIComponent(split[1]);
}

And here you have got your empObj back to file2.js which you have used in FIle1.js from another page.

Hope you got it.

  • FYI I'm not loading Both the files so , I can't use it next sub sequent js file which is loaded in the new window with new html page. – Tanveer Apr 05 '17 at 06:31
  • but at least you can pass that object by query string using serialize method and then unserialize in to the new page where ever you want to use it. – Hardik Sukhadiya Apr 05 '17 at 06:35
  • Exactly !! , So this what I'm asking how i can pass it from my code snippet where I'm setting the attribute onCLick , and also how I can access it in the File1.js – Tanveer Apr 05 '17 at 06:42
  • empObj = {'name' : "Abc"}; var param = ''; for (var p in empObj) { if (empObj.hasOwnProperty(p)) { param += encodeURIComponent(p) + "=" + encodeURIComponent(empObj[p]) + "&"; } } hrefLink.setAttribute('onClick',"window.open('/App/home/happyPath?'+param, '_blank', 'toolbar=yes,scrollbars=yes,resizable=yes,top=300,left=60,width=1100,height=650')"); Hope you got it.. – Hardik Sukhadiya Apr 05 '17 at 06:59
  • :( No, throwing error on this line `hrefLink.setAttribute('onClick',"window.open('/App/home/happ‌​yPath?'+param, '_blank', 'toolbar=yes,scrollbars=yes,resizable=yes,top=300,left=60,wi‌​dth=1100,height=650'‌​)");` – Tanveer Apr 05 '17 at 07:46
  • which error ? can you see console and say me which error is showing ? – Hardik Sukhadiya Apr 05 '17 at 07:58
  • **SyntaxError: Invalid character '\u8204'**. this is the error at console. , I guess something issue with the quotes .. – Tanveer Apr 05 '17 at 08:02
  • serialize = function(obj) { var str = []; for(var p in obj) if (obj.hasOwnProperty(p)) { str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p])); } return str.join("&"); } empObj = { 'name': 'Abc'}; var param = serialize(empObj); var href= "/App/home/happ‌yPath?"+ param; var hrefLink = document.createElement('a'); hrefLink.setAttribute('onClick', 'window.open(\''+href+'\', \'_blank\', \'toolbar=yes,scrollbars=yes,resizable=yes,top=300,left=60,width=1100,height=650\')'); Use above code and say me working or not ? – Hardik Sukhadiya Apr 05 '17 at 09:48
  • No its giving same error... SyntaxError: Invalid character '\u8204'. – Tanveer Apr 05 '17 at 09:58
  • Now its working...That URL was taking some special char.. Now its appending param. Thanks lot :-) , Now i'm passing that param from File1.js now how to access it at File2.js – Tanveer Apr 05 '17 at 10:15
  • Now you can get each values from query string of url like this: var queryString = window.location.search; queryString = queryString.replace("?", ''); var empObj = {}; var pairs = queryString.split('&'); for(i in pairs){ var split = pairs[i].split('='); empObj[decodeURIComponent(split[0])] = decodeURIComponent(split[1]); } And here you have got your empObj back to file2.js which you have used in FIle1.js. Hope you got it. – Hardik Sukhadiya Apr 05 '17 at 10:41
  • @Tanveer it is not the answer to your original answer. The Answer is in the comments. Please let him update his answer and than mark it as answer. – DomeTune Apr 05 '17 at 14:19
  • @HardikSukhadiya Please update your answer with the parts of the comments. The current version of your answer does not answers the original question. – DomeTune Apr 05 '17 at 14:21
  • @Tanveer he updated his answer, did this solved your question ? – DomeTune Apr 07 '17 at 08:35
1

I show you a simple way of modular javascript programming, and how you can access the variable from each module.

How the module-programming works:

  1. We create a function to have a kind of class. In this function everything is not accessable from the outside. Why we do this? Everyone can easily open the developer tools and execute functions or change variables without even using a debugger / breakpoint. We want to avoid this.
  2. The parameter for the function are our module, the current window, the current document and an undefined. Why we do this? We use the module to ensure what object we use for the class. The window, document and undefined ensure that we are using the same objects as outside of the function. (iFrames, ...). The parameter undefined wont be asigned, this ensures that we have a 100% null value.
  3. We execute the function / class immediately. As this we can create separate javascript-files.

The module parameter is used to assign the module to the window with a specific name. In the example fileOne and fileTwo. If we create window.someObj = {};, this object can be accessed in the window from everywhere. window.someObj.hello = "Hello"; can be accessed by someObj.hello. The function get this object and add all "global" functions and objects to it with module.fn = function(){}; module.obj = {}; module.variable = "";

//Simple modular javascript
(function (module, window, document, undefined) {
  module.someVariable = "Hello";
})((window.fileOne = {}), window, document);

(function (module, window, document, undefined) {
  module.otherVariable = "World";

  module.logBoth = function(){
    console.log(fileOne.someVariable + " " + module.otherVariable);
    //console.log(fileOne.someVariable + " " + fileTwo.otherVariable);
  }
})((window.fileTwo = {}), window, document);

fileTwo.logBoth();

//In your case you change your HTML, so all declared variables at runtime get lost. You need to store them.

(function (module, window, document, undefined) {
  var someVariable = "Hello";

  module.changeValue = function(){
    someVariable = "Hello World";
  }

  module.switchPage = function(){
    localStorage.setItem("someNameForTheItem", JSON.stringify(someVariable));
    //open your page here
  }
})((window.fileOne = {}), window, document);

(function (module, window, document, undefined) {
  var someVariable = "Hello";

  module.init = function(){
    //execute the function after document is ready.
    var localItem = localStorage.getItem("someNameForTheItem");
    someVariable = JSON.parse(localItem);
    console.log(someVariable);
  }
})((window.fileTwo = {}), window, document);

//wont work in the sandboxed window, because of CORS-Error. We cannot add item to the local Storage. Test it in your environment.
fileOne.switchPage();
fileTwo.init();

I am sorry for my bad english skills. Hope you understand, what i am trying to say.

DomeTune
  • 1,401
  • 10
  • 21
  • Here what your referring to window.fileOne and window.fileTwo. I didn't get , in my case how I can utilise this. – Tanveer Apr 05 '17 at 07:48
  • I dont know your javascript style. In your case the most important aspect is the `localStorage`. In your `File1.js` you need to add the `empObj` to the `locatStorage` (`localStorage.setItem("empObj", JSON.stringify(empObj));`) . At the `NewWindow.html` `File2.js` is loaded. There you need to load the item again `var empObj = JSON.parse(localStorage.getItem("empObj"));`. You will need to do `value-check` for `null`, `undefined` and `empty String`. To use the modular programming style you need to create a `File1.js` with the first three lines of the example code. For more chat with me :-) – DomeTune Apr 05 '17 at 08:16
0

A variable declared in global scope should be avaiable to all subsequent scripts after it is declared. So,

<script src="/File1.js"></script>
<script src="/File2.js"></script>

would mean "empObj" should be available in File2.js.

Another case would be if you are using implementing your code inside IIFE

(function(){
 //var empObj = {'name' : "Abc"};
}());

in which case you would need to return your empObj object.

Hope this helps..

dattebayo
  • 1,362
  • 9
  • 4
  • ya I got your point , but my question is how can access the **empObj** in the **File2.js** on click of my href link or How pass this **empObj** to File2.js – Tanveer Apr 05 '17 at 06:08
0

You could use window.name for storing even an object if you serialize it and parse back as json. You should not use window.name for storing secure data, as it can be retrieved by other scripts.

itacode
  • 3,721
  • 3
  • 21
  • 23