Memory leaks when embed YouTube videos in Metro App using iframe - javascript

I want to play some YouTube video in my Metro app. I embed YouTube video in my app using YouTube Iframe API(Link). Then I meet a serious problem of memory leak. If I embed a YouTube video and then remove it, the memory will increase about 5MB and nerver decrease any more. Demo code is here:
default.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>iframeTest</title>
<!-- WinJS references -->
<link href="//Microsoft.WinJS.1.0/css/ui-dark.css" rel="stylesheet" />
<script src="//Microsoft.WinJS.1.0/js/base.js"></script>
<script src="//Microsoft.WinJS.1.0/js/ui.js"></script>
<!-- iframeTest references -->
<link href="/css/default.css" rel="stylesheet" />
<script src="/js/default.js"></script>
</head>
<body style ="">
<button id="remove" style="display:block; float:left;">remove a video</button>
<button id="add" style="display:block; float:left;">add a video</button>
</body>
</html>
default.js fragment:
document.getElementById("remove").addEventListener("click", function () {
var ifrs = document.querySelectorAll('div');
if (ifrs.length > 0) {
document.body.removeChild(ifrs[ifrs.length - 1]);
}
});
document.getElementById("add").addEventListener("click", function(){
var testYoutubeDiv = document.createElement('div');
testYoutubeDiv.style.cssFloat = 'left';
testYoutubeDiv.style.width = '400px';
testYoutubeDiv.style.height = '300px';
MSApp.execUnsafeLocalFunction(function () {
testYoutubeDiv.innerHTML = "<iframe id='player' type='text/html' width='400' height='300' src='http://www.youtube.com/embed/u1zgFlCw8Aw?enablejsapi=1&origin=http://example.com' frameborder='0'></iframe>";
});
document.body.appendChild(testYoutubeDiv);
});
Then, I write a similar .html file and test it in IE10.0 and Chrome. I find IE10.0 also has memory leak problem but chrome has not. And the memory leak problem in IE10.0 is less serious than in Metro App.
test html code was here:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>iframeTest</title>
<script type = "text/javascript">
function load() {
document.getElementById("remove").addEventListener("click", function () {
var ifrs = document.querySelectorAll('div');
if (ifrs.length > 0) {
document.body.removeChild(ifrs[ifrs.length - 1]);
}
});
document.getElementById("add").addEventListener("click", function () {
var testYoutubeDiv = document.createElement('div');
testYoutubeDiv.style.cssFloat = 'left';
testYoutubeDiv.style.width = '400px';
testYoutubeDiv.style.height = '300px';
testYoutubeDiv.innerHTML = "<iframe id='player' type='text/html' width='400' height='300' src='http://www.youtube.com/embed/u1zgFlCw8Aw?enablejsapi=1&origin=http://example.com' frameborder='0'></iframe>";
document.body.appendChild(testYoutubeDiv);
});
}
</script>
</head>
<body onload ="load()">
<button id="remove" style="display:block; float:right;">remove a video</button>
<button id="add" style="display:block; float:right;">add a video</button>
</body>
</html>
I notice that IE(and maybe Metro App) does not use WebKit Engine to deal with javascript code. Is there any way to reduce memory leak in Metro App?

Create an iframe in html file
<iframe id="ifr_video"></iframe>
And then add a source to that iframe using javascript, while adding source find the id of YouTube URL by spliting, for example if the YouTube URL is http://www.youtube.com/watch?v=ZnehCBoYLbc, the ID is ZnehCBoYLbc, then define the source like the following for finding ID and adding source
var Url_splits = Youtube_Video_url.split("/");
var Url_length = Url_splits.length;
var Ytube_id = Url_splits[(Url_length - 1)];
document.getElementById("ifr_video").src = "http://www.youtube.com/embed/" + Ytube_id;
In HTML
<video id="VideoSource" style="border:1px solid black;" controls="controls" ></video>
<iframe class="youtube-player" id="ifr_video" type="text/html" width=100% height=100% allowfullscreen frameborder="0"></iframe>
In JS (inside ready function)
id("VideoSource").msPlayToSource.connection.addEventListener("statechanged", playToSrcStateChangeHandler);
function playToSrcStateChangeHandler(eventIn) {
var states = Windows.Media.PlayTo.PlayToConnectionState;
if (eventIn.currentState === states.disconnected) {
WinJS.log && WinJS.log("PlayTo connection state: Disconnected", "sample", "status");
} else if (eventIn.currentState === states.connected) {
WinJS.log && WinJS.log("PlayTo connection state: Connected", "sample", "status");
} else if (eventIn.currentState === states.rendering) {
WinJS.log && WinJS.log("PlayTo connection state: Rendering", "sample", "status");
}
}
Video_Path = "http://www.youtube.com/embed/" + new_id;
//new_id is the Youtube video id For example,..
in http://www.youtube.com/watch?v=ZnehCBoYLbc , id is ZnehCBoYLbc
function playYouTubeVideo(Video_Path) {
document.getElementById("ifr_video").src = Video_Path;
id("VideoSource").style.display='none';
}
function playWebContent(Video_Path) {
document.getElementById("ifr_video").style.display = 'none';
var localVideo = id("VideoSource");
var videoStabilization = Windows.Media.VideoEffects.videoStabilization;
localVideo.src = Video_Path;
localVideo.play();
}
Reference: http://code.msdn.microsoft.com/windowsapps/Media-PlayTo-Sample-fedcb0f9

Related

Why can I write to sessionStorage from an iframe on the first try, but not any consecutive tries? (Chrome Version 74)

This issue has shown up in the latest version of Chrome (74.0.3729.108). This is unique to the local filesystem, as I have other ways of loading up neighboring documents in iframes when the app is on a server.
In my app, we have been able to load up documents from the filesystem with JavaScript by writing iframes to the DOM, and then having the document in the iframe write it's innerHTML to sessionStorage. Once the iframe is done loading, we catch that with the onload attribute on the iframe and handle getting the item written to sessionStorage.
I have narrowed this down to some bare-bones code and found that this works only on the first try, and then any tries after the first fail.
Here is a minimal HTML document:
<!DOCTYPE html>
<html>
<head>
<title>Chrome iFrame Tester</title>
<script src="iframe-load.js"></script>
</head>
<body onload="OnLoad()">
<div id="result"></div>
</body>
</html>
Here is the JavaScript:
var urls = ['file://C:/Users/afrench/Documents/Other/Misc%20Code/Chrome%20iFrame/Doc1.html',
'file://C:/Users/afrench/Documents/Other/Misc%20Code/Chrome%20iFrame/Doc2.html'];
HandleLoad = function () {
'use strict';
var data;
try {
data = window.sessionStorage['data'];
delete window.sessionStorage['data'];
} catch (ignore) {
// something went wrong
}
var container = document.getElementById('container');
window.document.body.removeChild(container);
if (data !== null && data !== undefined) {
var resultContainer = document.getElementById('result');
resultContainer.innerHTML += data;
}
if (urls.length > 0) {
OnLoad();
}
}
function OnLoad() {
var url = urls[0];
if (url) {
urls.splice(0, 1);
var container = document.createElement('div');
container.id = 'container';
container.style.visibility = 'hidden';
window.document.body.appendChild(container);
container.innerHTML = '<iframe src="' + url + '" onload="HandleLoad();"></iframe>';
}
}
In the filesystem, we have the HTML written into index.html, and right next to it are two minimal HTML files, Doc1.html and Doc2.html. Their contents are both identical except the identifying sentence in the body's div:
Neighbor document HTML:
<!DOCTYPE html>
<html>
<head>
<title>Chrome iFrame Tester</title>
<script>
function OnLoad() {
try {
window.sessionStorage['data'] = window.document.body.innerHTML;
} catch {
// no luck
}
}
</script>
</head>
<body onload="OnLoad()">
<div>This is Doc 1's content!</div>
</body>
</html>
When this is run, we should see the content HTML of the two neighbor documents written to the result div in index.html.
When I run this minimal example, I can see that the content is successfully written to sessionStorage and then to the DOM for the first document, but the next try fails. What can I do to get it to work consistently, and what is happening here that it fails?
I'm not sure what is causing the weird behavior, so hopefully someone else can provide some insight on what exactly is going on here.
In the meantime, here is an alternative solution using window.postMessage:
index.html
<!DOCTYPE html>
<html>
<head>
<title>Chrome iFrame Tester</title>
<script src="iframe-load.js"></script>
</head>
<body onload="OnLoad()">
<div id="result"></div>
</body>
</html>
iframe-load.js
var urls = ['file://C:/Users/afrench/Documents/Other/Misc%20Code/Chrome%20iFrame/Doc1.html',
'file://C:/Users/afrench/Documents/Other/Misc%20Code/Chrome%20iFrame/Doc2.html'];
window.addEventListener('message', event => {
'use strict';
var data = event.data;
var container = document.getElementById('container');
window.document.body.removeChild(container);
if (data) {
var resultContainer = document.getElementById('result');
resultContainer.innerHTML += data;
}
if (urls.length > 0) {
OnLoad();
}
})
function OnLoad() {
var url = urls.shift();
if (url) {
var container = document.createElement('div');
container.id = 'container';
container.style.visibility = 'hidden';
window.document.body.appendChild(container);
container.innerHTML = '<iframe src="' + url + '"></iframe>';
}
}
Doc1.html
<!DOCTYPE html>
<html>
<head>
<title>Chrome iFrame Tester</title>
<script>
function OnLoad() {
window.parent.postMessage(window.document.body.innerHTML, '*');
}
</script>
</head>
<body onload="OnLoad()">
<div>This is Doc 1's content!</div>
</body>
</html>

html5 movie playlist, How to Count file

i have this code for autoplay (playlist) movie
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Movie Playlist</title>
<script>
var videoPlayer;
var video_count = 1;
window.onload = function (){
videoPlayer = document.getElementById("homevideo");
videoPlayer.addEventListener("ended", function (){
video_count++;
if (video_count == 6) video_count = 1;
var nextVideo = video_count+".mp4";
videoPlayer.src = nextVideo;
}, false);
}
</script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/meyer-reset/2.0/reset.min.css">
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<div style="width:100%;margin:0px auto;">
<video id="homevideo" width="100%" autoplay autobuffer src="1.mp4"></video>
</div>
on the code above, i have 5 .mp4 movie, but if i have more than 5 .mp4 movie, the 6.mp4, 7.mp4 and other will not be played. so, how can i dynamically set the movie count pure using html5 or javascript?
You are better off having your server provide this information.
But for your existing approach, I'm assuming your video names are in sequential order ... so 1.mp4, 2.mp4, 3.mp4, etc ... so you could keep looping through the videos while increasing the count, and once a video fails to load at a given video_count, you can know that it is the limit and loop back to the start if you wanted.
function videoExists(videoUrl){
var http = new XMLHttpRequest();
http.open('HEAD', videoUrl, false);
http.send();
return http.status != 404;
}
So, for example ...
var videoPlayer;
var video_count = 1;
var video_max = 0;
window.onload = function (){
videoPlayer = document.getElementById("homevideo");
videoPlayer.addEventListener("ended", function (){
var nextVideo = (video_count+1)+".mp4";
if(video_count <= video_max || videoExists(nextVideo)){
videoPlayer.src = nextVideo;
video_count++;
}else{
video_max = video_count;
//reset back to original video
video_count = 1;
videoPlayer.src = video_count+".mp4";
}
}, false);
}
I didn't test the code, but you should get the idea. Please let me know if you have any questions about this approach.

How to get the ParentElement of Object Tag?

I have a SVG graphic embedded via object tag.
<!DOCTYPE html>
<html>
<head>
<title>myTitle</title>
<script type="text/javascript" src="script.js"></script>
<link href="box.css" rel="stylesheet" type="text/css" media="screen" />
</head>
<body>
<div id ="objectcontainer">
<div id="displaybox" style="display: none;"></div>
<object id = "mainSVG" type="image/svg+xml" data="map_complete.svg">
<img id="svgPic" src="map_complete.svg" alt="Browser fail"/>
</object>
</div>
</body>
</html>
In the SVG is a link:
<a id="emerBtn" xlink:href="emergency.html" onmouseover="return playVideo()" target="_parent">
The mouse over event should trigger the following:
function playVideo(){
//not working, all the time null
var doc = document.parentNode;
var elem = document.parentElement;
var otherElem = document.documentElement.parentElement;
//working if triggered from index.html
var thediv = document.getElementById('displaybox');
if(wasViewed == false) //show only one time
{
if(thediv.style.display == "none"){
wasViewed = true;
thediv.style.display = "";
thediv.innerHTML = "<div id='videocontainer'><video autoplay controls style='display:block; margin-left:auto;" +
"margin-right:auto; margin-top:150px; margin-bottom:auto; width:600px'>" +
"<source src='video.mp4' type='video/mp4'>HMTL5-Video not supported!</video>" +
"</div><a href='#' onclick='return palyVideo();'>CLOSE WINDOW</a>";
}else{
thediv.style.display = "none";
thediv.innerHTML = '';
}
} //close anyhow
else{
thediv.style.display = "none";
thediv.innerHTML = '';
}
return false;
}
My problem is, that i cannot access the "displaybox" from the svg.
I tried .parentNode, .parentElement, document.documentElement.parentElement etc.
But all the time the parent element/node is null.
Does anyone know how to access the "outer" HTML elements from the object/svg?
An SVG inside an object creates a nested browsing context.
To access elements outside this child document, you need to access the parent document:
function playVideo() {
// ...
var parentDoc = window.parent.document;
var displayBox = parentDoc.getElementById('displaybox');
// ...
}

Playing a loop of videos by javascript

I am trying to write code to play a continous loop of two videos. I have tried to do so by this code, but it has not been done. Being new to html5 and javascript need help to make required corrections.
<!doctype html>
<html><head>
<script>
var videoSource = new Array();
videoSource[0]="videfirst.mp4";
videoSource[1]="videosecond.mp4";
var videoCount = videoSource.length;
document.getElementById("myVideo").setAttribute("src",videoSource[0]);
function videoPlay(videoNum)
{
document.getElementById("myVideo").setAttribute("src",videoSource [videoNum]);
document.getElementById("myVideo").load();
document.getElementById("myVideo").play();
}
document.getElementById('myVideo').addEventListener ('ended',myHandler,false);
function myHandler() {
i++;
if(i == (videoCount-1)){
i = 0;
videoPlay(i);
}
else{
videoPlay(i);
}
}
</script>
</head>
<body>
<video controls height="180" width="300" id="video" >
</video>
</body>
</html>

HTML 5 media stream for video recording issue on record function

I wrote html 5 code for video recording and uploading. When click on start button it will produce a javascript error.
"TypeError: webcamstream.record is not a function streamRecorder = webcamstream.record();"
"TypeError: streamRecorder is undefined streamRecorder.getRecordedData(postVideoToServer);"
It is only for mozilla browser.Please help me...Code is
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
<script type="text/javascript">
var streamRecorder;
var webcamstream;
function enter()
{
if (navigator.mozGetUserMedia) {
navigator.myGetMedia=navigator.mozGetUserMedia;
navigator.myGetMedia({video: true}, connect, error);
}
else {
alert("N");
}
function connect(stream)
{
var video = document.getElementById("my_video");
video.src = window.URL ? window.URL.createObjectURL(stream) : stream;
webcamstream = stream;
video.play();
}
function error(e) { console.log(e); }
}
function startRecording()
{
alert('STARTING');
streamRecorder = webcamstream.record();
setTimeout(stopRecording, 10000);
}
function stopRecording()
{
alert('STOP');
streamRecorder.getRecordedData(postVideoToServer);
}
function postVideoToServer(videoblob) {
alert ('start video uploaded');
var data = {};
data.video = videoblob;
data.metadata = 'test metadata';
data.action = "upload_video";
jQuery.post("http://www.kongraju.in/uploadvideo.php", data, onUploadSuccess);
}
function onUploadSuccess() {
alert ('video uploaded');
}
</script>
<title>Untitled Document</title>
</head>
<body>
<canvas width="640" height="480" id="c"></canvas>
<input type="button" value="START CAMERA" onClick="enter()"/>
<input type="button" value="START RECORD" onClick="startRecording()"/>
<input type="button" value="STOP RECORD" onClick="stopRecording()"/>
<video id="my_video" width="640" height="480"/>
</body>
</html>
According to the specification draft of the getMediaStream API there is no method called record() W3C mediacapture draft
You can try to achieve recording by drawing each frame on a canvas and saving it to a temporary Image File using the new File System API. Maybe I can provide you an example later on. It has already been done using Webkit-Engine. See here

Categories

Resources