Search code examples
javascripthtmlgoogle-chrome-appsandbox

Chrome App : How to update the content of an element of a secondary window created in the main window of a Chrome App?


i want to create a simple chrome App which launches a window, 'window.html', which contains 2 buttons.

1/ #btn1 creates a new window, loading "video.html". A video player,
playing "file1.webm".

2/ #btn2 updtates the source of the video from "file1.webm" to
"file2.webm".

The first part is trivial :)

The second part is tricky.

Is it possible ?

You'll find my files below.

Thank you :)

<!DOCTYPE html>
<html >
<head>

	<title>Chrome : Multiple Window</title>
	<link href="./css/main.css" rel="stylesheet">
	<script src="./js/jquery.min.js"></script>
	<script src="./js/test.js"></script>
</head>
<body>
	<button id="btn1" type="button" >Launch video Player</button>
	<button id="btn2" type="button" >Update Video</button>
</body>
</html>

$(document).ready(function() {
	$("#btn1").click(function(){
	chrome.app.window.create('video_window.html', {"width":1280, "height": 720});
});
$("#btn2").click(function(){
		$('#myvideo video source').attr('src', './video/avatar.webm');
	});
});

<!DOCTYPE html>
<html>
<head>
	<link href="./css/video.css" rel="stylesheet">
</head>
<body>
	<div class="wrapper">
		<video id="myvideo" autoplay loop>
			<source src="./video/the_master.webm" type="video/webm">
			</video>
		</div>
	</body>
</html>


Solution

  • chrome.app.window.create accepts a callback which will be invoked with the created window. You can store a reference to this window, and then either execute functions directly on it, or use window.postMessage to communicate with it.

    var videoWindow = null;
    
    $("#btn1").click(function() {
      chrome.app.window.create('video_window.html', {
        "width": 1280,
        "height": 720
      }, function(window) {
        videoWindow = window.contentWindow;
      });
    });
    
    $("#btn2").click(function() {
      videoWindow.doSomething('./video/avatar.webm');
    });
    

    Another option, is to use the chrome runtime API to communicate:

    chrome.runtime.sendMessage("do-stuff")
    
    chrome.runtime.onMessage.addListener(function(e) {
        // do stuff
    })