Reputation: 769
How to transfer control to new window? Im working on a chrome packaged app with multi-window functionality. Suppose i click on "new window" and it opens up a new window this is the code im using:
background.js:
function create_window(opt_options)
{
chrome.app.window.create("main.html", opt_options,
});
}
Right after creating a new window im simply populating the value in the div
main.html
<html class="full-height">
<head>
<meta charset="utf-8">
<script src="jquery-2.0.2.js"></script>
<script src="main.js"></script>
</head>
<body>
<div id="username">Guest</div>
In main.html there a button that called the function for new function from background.js and add username in the div:
main.js
$(".menu-new-window").click(function() {
create_window()
$("user_name").html("John Doe");
});
The basic flow is, i select a user "John" from the list (parent/first window), a new window will open and John will be populated in the head section (div id username) of the new window. But after opening a new window it adds John in the parent window instead of new window. This happens whenever i open a new window, it always update its parent window.
I've just started developing the app so there's not much code to display, i've displayed some basic code of how im trying to work with multi-windows.
Please let me know if my question is not clear enough. Thanks!
Upvotes: 0
Views: 164
Reputation: 77541
As wOxxOm mentions, when you execute code within a document, that affects that document. Even just theoretically, how would your particular code know which window you mean?
There are probably 4 broad methods you can use, and I'm not saying they are exhaustive. I also won't go into too much detail.
Open a window with some parameters encoded in the URL
You can use either query parameters or the URL fragment to pass a (small) amount of data to the new window. E.g.:
chrome.app.window.create("main.html#u=" + encodeURIComponent("John Doe"));
and then decode location.hash
in the other window when it opens.
The problem with that is: you can't pass much information this way.
Use Messaging. chrome.runtime.sendMessage
can be used to broadcast some data to all parts of the app. The problem with it, though, is to determine which part of the app should listen.
Use chrome.storage
. This is a shared storage that your original window can write to before calling a new window, and the new window can read from it. There is again some problem with identifying windows, but it's easier to avoid.
A direct way to access the new window is available if you do it from the callback of window creation.
Namely, the contentWindow
property of AppWindow
.
chrome.app.window.create(
"main.html",
opt_options,
function(appWin) {
otherWindow = appWin.contentWindow;
otherWindow.username = "John Doe";
}
);
// And in the other window
window.onload = function() {
// You can use `username` here
}
It's even given as a sample in the docs.
Upvotes: 1