Reputation: 7527
I have created a new window with this piece of code and tried to send some data but the function is not called, maybe I'm doing it wrong?
script.js on index.html
var path = require('path');
element.onclick = function(){
var win = gui.Window.get(window.open('listdir.html'));
var location = path.resolve(process.cwd(),'fontsFolder');
win.eval(null, 'listdir("'+location+'")'); //Is there a node function to parse '\'?
};
listdir.js on listdir.html
function listdir(directory){
alert("directory "+directory); //never called
}
Error:
ReferenceError: listdir is not defined
at <anonymous>:1:1
at Window.init.Window.eval (window_bindings.js:486:16)
at HTMLLIElement.element.onclick (file:///C:/../AppData/Local/Temp/nw3528_1882/js/script.js:29:12)
Upvotes: 4
Views: 3721
Reputation: 5084
Okay, this might not be the right answer for the question "How to call a function in another window", but an answer for your initial problem "How to send parameters to new window" (before editing the title).
As I'm an enthusiast of the new storage objects in HTML5, I would synchronize the windows over sessionStorage
(so all passed parameters will survive the current new window lifetime, but not afterwards).
My working solution:
index.html (the initial window)
<!DOCTYPE html>
<html>
<body>
Test <a href="">Click</a>
<script src="jquery-1.11.1.min.js"></script>
<script>
var mySharedObj = {
'one': 1,
'two': 2,
'three': 3
};
// node-webkit specific
var gui = require('nw.gui');
$('a').click(function() {
var win = gui.Window.get(window.open('index2.html'));
win.eval(null, 'sessionStorage.setItem(\'mySharedJSON\', \''+JSON.stringify(mySharedObj)+'\');');
});
</script>
</body>
index2.html (the new window that will be opened via window.open
call:
<!DOCTYPE html>
<html>
<body>
Test 2:
<script src="jquery-1.11.1.min.js"></script>
<script>
$(document).ready(function() {
// Process sharedObj when DOM is loaded
var mySharedObj = JSON.parse(sessionStorage.getItem('mySharedJSON'));
// Now you can do anything with mySharedObj
console.log(mySharedObj);
});
</script>
</body>
So, how does it work? window.eval
(see documentation here) needs source code of scripts, that may be run in the context of the newly created window. I guess, your first try didn't work, as the script will be executed just in the moment the window is created, thus the DOM is not yet parsed and no JavaScript functions are available at that moment. So there are only the basic functions available (the window
object). So we're passing in a function that will store a serialized JSON in the window.sessionStorage. That way, you are able to access it from all functions in the new window.
Again: This is not the correct answer for general usage, but it might fit for your problem.
Upvotes: 1