How to get rid of the loading progress in Facebook Instant Games with Phaser - facebook

I am developping a game for Facebook instant games with Phaser 2 CE, and i don't like the loading progress shown at the starting point, how can i get rid of it ?
I am using the default example given in the Quick Start page
FBInstant.initializeAsync()
.then(function() {
var images = ['phaser2'];
for (var i=0; i < images.length; i++) {
var assetName = images[i];
var progress = ((i+1)/images.length) * 100;
game.load.image('./assets/' + assetName + '.png');
// Informs the SDK of loading progress
FBInstant.setLoadingProgress(progress);
}
});

You can try something like given in this example like the code bellow then create your game, i know it's not clean but it works
FBInstant.initializeAsync()
.then(function() {
FBInstant.setLoadingProgress(50);
FBInstant.setLoadingProgress(100);
});

I have tryed something interesting but it doesn't answers the question according to this example
var sprite;
var PixelW = window.innerWidth;
var PixelH = window.innerHeight;
var game = new Phaser.Game(PixelW, PixelH, Phaser.AUTO, 'game', { preload: preload, create: create, update: update });
function preload() {
game.load.onLoadStart.add(loadStart, this);
game.load.onFileComplete.add(fileComplete, this);
startLoading();
}
function startLoading () {
game.load.image('logo1', 'assets/sprites/phaser1.png');
game.load.image('logo2', 'assets/sprites/phaser2.png');
game.load.image('dude', 'assets/sprites/phaser-dude.png');
game.load.image('ship', 'assets/sprites/phaser-ship.png');
game.load.image('mushroom', 'assets/sprites/mushroom.png');
game.load.image('mushroom2', 'assets/sprites/mushroom2.png');
game.load.image('diamond', 'assets/sprites/diamond.png');
game.load.image('bunny', 'assets/sprites/bunny.png');
game.load.start();
}
function create() {
game.stage.backgroundColor = 0x3b5998;
game.scale.scaleMode = Phaser.ScaleManager.SHOW_ALL;
sprite = game.add.sprite(game.world.centerX, game.world.centerY, 'dude');
sprite.inputEnabled = true;
sprite.events.onInputDown.add(myHandler, this);
var text = game.add.text(10, 10, PixelW + " " + " " + PixelH, { font: "65px Arial", fill: "#ffff00", align: "center" });
}
function loadStart() {
}
// This callback is sent the following parameters:
function fileComplete(progress, cacheKey, success, totalLoaded, totalFiles) {
FBInstant.setLoadingProgress(progress);
//console.log(cacheKey + " " + progress);
}
function myHandler() {
sprite.anchor.setTo(0.5, 0.5);
sprite.x = Math.floor(Math.random() * PixelW);
sprite.y = Math.floor(Math.random() * PixelH);
}
function update() {
}
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<script src="https://connect.facebook.net/en_US/fbinstant.6.0.js"></script>
<script src="phaser.min.js" type="text/javascript"></script>
<title></title>
</head>
<body>
<script type="text/javascript">
var p = 0;
FBInstant.initializeAsync()
.then(function() {
//FBInstant.setLoadingProgress(50);
//FBInstant.setLoadingProgress(100);
});
// Once all assets are loaded, tells the SDK
// to end loading view and start the game
FBInstant.startGameAsync()
.then(function() {
// Retrieving context and player information can only be done
// once startGameAsync() resolves
var contextId = FBInstant.context.getID();
var contextType = FBInstant.context.getType();
var playerName = FBInstant.player.getName();
var playerPic = FBInstant.player.getPhoto();
var playerId = FBInstant.player.getID();
// Once startGameAsync() resolves it also means the loading view has
// been removed and the user can see the game viewport
// game.start();
});
</script>
<div id="game"></div>
<script src="game.js" type="text/javascript"></script>
</body>
</html>

I use the methods below, I increase the loading percent after each file is loaded with Phaser. Also I include a try catch so that when testing local game play the game does not crash.
preload: function () {
try{
FBInstant.initializeAsync()
.then(function() {
});
}
catch(err) {
console.log('FB Instant Games Error: No Internet Connected');
}
this.load.image('gameItem1', 'assets/sprite/game_item1.png');
this.load.image('gameItem2', 'assets/sprite/game_item2.png');
}
And then...
startFacebookGame: function(){
try{
FBInstant.startGameAsync()
.then(function() {
// Retrieving context and player information can only be done
// once startGameAsync() resolves
var contextId = FBInstant.context.getID();
var contextType = FBInstant.context.getType();
var playerName = FBInstant.player.getName();
var playerPic = FBInstant.player.getPhoto();
var playerId = FBInstant.player.getID();
// Once startGameAsync() resolves it also means the loading view has
// been removed and the user can see the game viewport
});
}
catch(err) {
console.log('Analytics Connection Error');
}
},
fileComplete: function(progress, cacheKey, success, totalLoaded, totalFiles) {
try{
FBInstant.setLoadingProgress(progress);
}
catch(err) {
console.log('FB Instant Games progress Failed: No Internet Connected.');
}
//console.log("Progress: " + progress);
},

Here's how I do it. You can build out from there.
function preload() {
// Load some assets
FBInstant.setLoadingProgress(100)
}
function create() {
FBInstant
.startGameAsync()
.then(() => {
// Here you can now get users name etc.
console.log(this)
})
}
FBInstant.initializeAsync()
.then(() => {
new Phaser.Game({
type: Phaser.AUTO,
width: window.innerWidth,
height: window.innerHeight,
scene: {
preload,
create
}
})
})

Related

Show HTML in window with OK button in VSCode extension

I need to insert text after the cursor if the user agrees. I can't find anything in the documentation for my task.
Mission of my extension:
user writes code
then he calls the extension
it sends all code to a server
returns and shows some code in an additional window with an "OK" button
pressing the "OK" button inserts the server's response after the cursor
I have a problem with point 4. I can't find a method to show the additional window with an "OK" button.
All code from extension.js:
function activate(context) {
console.log('"showText" active');
const commandId = 'extension.showText'
let disposable = vscode.commands.registerCommand(commandId, function () {
const text = editor.document.getText()
let options = {
method: 'GET',
uri: 'http://example.com:8081/',
body: {
text: text
},
json: true
}
rp(options)
.then(function (respString) {
console.log(respString);
// what should I call here?
// vscode.window.showInformationMessage(respString);
})
.catch(function(err) {
console.log(err);
});
});
context.subscriptions.push(disposable);
}
exports.activate = activate;
function deactivate() {
console.log('showText disactive');
}
module.exports = {
activate,
deactivate
}
It is not duplicate of How to handle click event in Visual Studio Code message box? because I need HTML page. And this decision just shows text message with confim button.
My decision is:
webview-sample
Webview API
My example:
// The module 'vscode' contains the VS Code extensibility API
// Import the module and reference it with the alias vscode in your code below
const vscode = require('vscode');
const workspace = vscode.workspace;
const window = vscode.window;
const rp = require("request-promise");
// this method is called when your extension is activated
// your extension is activated the very first time the command is executed
/**
* #param {vscode.ExtensionContext} context
*/
function activate(context) {
// Use the console to output diagnostic information (console.log) and errors (console.error)
// This line of code will only be executed once when your extension is activated
console.log('Extension activated');
// The command has been defined in the package.json file
// Now provide the implementation of the command with registerCommand
// The commandId parameter must match the command field in package.json
const commandId = 'extension.showText'
let disposable = vscode.commands.registerCommand(commandId, function () {
const editor = window.activeTextEditor;
const text = editor.document.getText();
console.log('For editor "'+ editor._id +'"');
let options = {
method: 'POST',
uri: URL,
body: {
text: text
},
json: true
};
rp(options)
.then(function (res) { // res
const panel = window.createWebviewPanel(
'type_id', // Identifies the type of the webview. Used internally
'Title', // Title of the panel displayed to the user
vscode.ViewColumn.Two, // Editor column to show the new webview panel in.
{
// Enable scripts in the webview
enableScripts: true
} // Webview options. More on these later.
);
panel.webview.html = res;
// Handle messages from the webview
// закрывать когда выбираешь другое окошко
window.onDidChangeActiveTextEditor(
ev => {
// console.log(ev._id, editor._id, editor);
ev && ev._id && ev._id != editor._id && panel.dispose();
}
)
// закрывать когда закрываешь окно
workspace.onDidCloseTextDocument(
textDocument => {
console.log("closed => " + textDocument.isClosed)
panel.dispose();
},
null,
context.subscriptions
);
// любая клавиша кроме enter - фильтр по префиксу
// если enter - поиск подсказок
workspace.onDidChangeTextDocument(
ev => {
console.log(ev);
if (ev && ev.contentChanges && ev.contentChanges.length
&& (ev.contentChanges[0].text || ev.contentChanges[0].rangeLength)) {
// do smth
} else {
console.error('No changes detected. But it must be.', ev);
}
},
null,
context.subscriptions
);
panel.webview.onDidReceiveMessage(
message => {
switch (message.command) {
case 'use':
console.log('use');
editor.edit(edit => {
let pos = new vscode.Position(editor.selection.start.line,
editor.selection.start.character)
edit.insert(pos, message.text);
panel.dispose()
});
return;
case 'hide':
panel.dispose()
console.log('hide');
return;
}
},
undefined,
context.subscriptions
);
panel.onDidDispose(
() => {
console.log('disposed');
},
null,
context.subscriptions
)
})
.catch(function(err) {
console.log(err);
});
});
context.subscriptions.push(disposable);
}
exports.activate = activate;
// this method is called when your extension is deactivated
function deactivate() {
console.log('Extension disactivated');
}
module.exports = {
activate,
deactivate
}
The example of res:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Title</title>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
</head>
<body>
<p id="text">Text</p>
<button onclick="useAdvise()">Use</button>
<button onclick="hideAdvise()">Hide</button>
<script>
const vscode = acquireVsCodeApi();
function useAdvise(){
let text_ = $(document).find("#text").text();
vscode.postMessage({command: 'use',text: text_})
}
function hideAdvise(){
vscode.postMessage({command: 'hide'})
}
</script>
</body>
</html>

Use getUserMedia with ionic get only black screen

Im testing some media features with ionic and im stuck while trying to set the camera output into a video tag using getUserMedia using this code:
navigator.getUserMedia = navigator.getUserMedia ||
navigator.webkitGetUserMedia ||
navigator.mozGetUserMedia;
if (navigator.getUserMedia) {
navigator.getUserMedia({ audio: false, video: { width: 500, height: 500 } },
function(stream) {
console.log("Im streaming!!", stream);
var video = document.querySelector('video');
console.log("video element", video);
video.src = window.URL.createObjectURL(stream);
video.onloadedmetadata = function(e) {
console.log("stream start");
video.play();
};
},
function(err) {
console.log("The following error occurred: " + err.name);
}
);
} else {
console.log("getUserMedia not supported");
}
this is the html:
<ion-pane>
<ion-header-bar class="bar-stable">
<h1 class="title">Ionic Blank Starter</h1>
</ion-header-bar>
<ion-content>
<video id="video" autoplay="autoplay" width="500" height="500"></video>
</ion-content>
</ion-pane>
i can actually get only a black screen. Is my approach right or im missing something?
I managed to reproduce the problem and solved it by using the constraints options. Using constraints you can set the sourceId that allows you to select between front or rear camera. Im sure that your device has no front camera and i guess this is why you are getting the black screen.
First we create our constraint options:
var constraints = {};
MediaStreamTrack.getSources (function(sources) {
sources.forEach(function(info) {
if (info.facing == "environment") {
constraints = {
video: {
optional: [{sourceId: info.id}]
}
};
}
})
})
Then we call the navigator.getUserMedia:
navigator.getUserMedia = navigator.getUserMedia ||
navigator.webkitGetUserMedia ||
navigator.mozGetUserMedia;
if (navigator.getUserMedia) {
navigator.getUserMedia(constraints,
function(stream) {
console.log("Im streaming!!", stream);
var video = document.querySelector('video');
console.log("video element", video);
video.src = window.URL.createObjectURL(stream);
video.onloadedmetadata = function(e) {
console.log("stream start");
video.play();
};
},
function(err) {
console.log("The following error occurred: " + err.name);
}
);
} else {
console.log("getUserMedia not supported");
}
Warning: MediaStreamTrack.getSources returns a promise so that means that if you try to run your navigator.getUserMedia code at once, it will fail. You will have to wrap it in a function and run it as a callback.
More info about camera and audio source selection can be found here:
https://developers.google.com/web/updates/2015/10/media-devices
also a nice example here:
https://simpl.info/getusermedia/sources/
The final solution to this problem is that getUserMedia require a runtime permission check to work. To achieve that i used this plugin. Then this worked like a charm:
cordova.plugins.diagnostic.requestRuntimePermission(function(status){
if(cordova.plugins.diagnostic.runtimePermissionStatus.GRANTED){
navigator.getUserMedia({video: true, audio: false}, function(localMediaStream) {
var video = document.querySelector('video');
video.src = window.URL.createObjectURL(localMediaStream);
video.onloadedmetadata = function(e) {
console.log('Stream is on!!', e);
};
}, errorCallback);
}
});

Ionic There is a Bug? ion-refresher and ion-infinite-scroll

I found an compatibility issue using the two mentioned components on same list, my html and js code below:
HTML:
<ion-content ng-controller="homeCtrl">
<ion-refresher on-refresh="loadNewContent()" pulling-text="LoadMore..." spinner="android"></ion-refresher>
<div ng-repeat="item in items">
<img ng-src="{{pathUrl+item['path']}}" style="height: auto;width:100%;">
</div>
<ion-infinite-scroll ng-if="hasMore" on-infinite="loadMoreContent()" spinner="spiral" distance="5" immediate-check="false"></ion-infinite-scroll>
</ion-content>
JavaScript:
JiCtrls.controller('homeCtrl', ['$scope', '$timeout', 'DbService', 'JsonService',
function ($scope, $timeout, DbService, JsonService) {
$scope.items = [];
$scope.hasMore = true;
var run = false;
loadData(0);
//下拉更新
$scope.loadNewContent = function () {
loadData(2);
// Stop the ion-refresher from spinning
$scope.$broadcast("scroll.refreshComplete");
};
//上拉更新
$scope.loadMoreContent = function () {
loadData(1);
$scope.$broadcast('scroll.infiniteScrollComplete');
};
function loadData(stateType) {
if (!run) {
run = true;
if ($scope.sql == undefined) {
$scope.sql = "select top 5 * from information ";
}
DbService.getData($scope.sql, '').success(function (data, status, headers, config) {
var convertData = JsonService.convertData(data);
if (stateType == 1 || stateType == 0) {
// $scope.items = $scope.items.concat(convertData);
for (var i = 0; i < convertData.length; i++) {
$scope.items.push(convertData[i]);
}
}
else {
for (var i = 0; i < convertData.length; i++) {
$scope.items.unshift(convertData[i]);
}
}
if (convertData == null || convertData.length <= 0) {
$scope.hasmore = false;
;
}
$timeout(function () {
run = false;
}, 500);
}).error(function (errorData, errorStatus, errorHeaders, errorConfig) {
console.log(errorData);
});
}
}
}
]);
Everything is normal in Chrome browser and Iphone, but in a part of the Android phone there is a big problem.When ion-refresher trigger on-refresh function,the on-infinite="loadMoreContent()" function will run indefinitely. So,What is the problem?
Try to put $scope.$broadcast("scroll.refreshComplete"); and $scope.$broadcast('scroll.infiniteScrollComplete'); into DbService.getData(...).success() callback, not in functions triggered by on-infinite and on-refresh.
Explanation:
When the user scrolls to the end of the screen, $scope.loadMoreContent which is registered with on-infinite is triggered. The spinner shows, and ion-infinite-scroll pauses checking whether the user has reached the end of the screen, until $scope.$broadcast('scroll.infiniteScrollComplete'); is broadcast, when it hides the spinner and resumes the checking.
In your code, imagine there's a 3s delay in network, no new item is added to the list in that 3s. As a result, the inner height of ion-content is never updated, so the check that determines whether the user has reached the end of the screen will always return true. And you effectively prevent ion-infinite-scroll from pausing this checking by broadcasting scroll.infiniteScrollComplete the moment on-infinite is triggered. That's why it will update indefinitely.
To improve your code quality and prevent future problems, you may need to call $scope.$apply in your DbService.getData().success() callback (depending on the implementation of getData) and manually notify ion-content to resize in the callback.
P.S. 来自中国的Ionic开发者你好 :-) 两个中国人讲英语真累啊
Update
I've made a codepen that combines both ion-refresher and ion-infinite-scroll, I think it's working pretty fine.
http://codepen.io/KevinWang15/pen/xVQLPP
HTML
<html ng-app="ionicApp">
<head>
<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
<title>ion-refresher + ion-infinite-scroll 2</title>
<link href="//code.ionicframework.com/nightly/css/ionic.css" rel="stylesheet">
<script src="//code.ionicframework.com/nightly/js/ionic.bundle.js"></script>
</head>
<body ng-controller="MyCtrl">
<ion-header-bar class="bar-positive">
<h1 class="title">ion-refresher + ion-infinite-scroll 2</h1>
</ion-header-bar>
<ion-content delegate-handle="mainScroll">
<ion-refresher on-refresh="doRefresh()">
</ion-refresher>
<ion-list>
<ion-item ng-repeat="item in list">{{item}}</ion-item>
</ion-list>
<ion-infinite-scroll
ng-if="hasMore"
on-infinite="loadMore()"
distance="1%">
</ion-infinite-scroll>
</ion-content>
</body>
</html>
JS
angular.module('ionicApp', ['ionic'])
.controller('MyCtrl', function($scope, $timeout, $q, $ionicScrollDelegate) {
/*
list of items, used by ng-repeat
*/
$scope.list = [];
var itemOffset = 0,
itemsPerPage = 5;
/*
used by ng-if on ion-infinite-scroll
*/
$scope.hasMore = true;
/*
isRefreshing flag.
When set to true, on data arrive
it first empties the list
then appends new data to the list.
*/
var isRefreshing = false;
/*
introduce a custom dataFetcher instance
so that the old fetch process can be aborted
when the user refreshes the page.
*/
var dataFetcher=null;
/*
returns a "dataFetcher" object
with a promise and an abort() method
when abort() is called, the promise will be rejected.
*/
function fetchData(itemOffset, itemsPerPage) {
var list = [];
//isAborted flag
var isAborted = false;
var deferred = $q.defer();
//simulate async response
$timeout(function() {
if (!isAborted) {
//if not aborted
//assume there are 22 items in all
for (var i = itemOffset; i < itemOffset + itemsPerPage && i < 22; i++) {
list.push("Item " + (i + 1) + "/22");
}
deferred.resolve(list);
} else {
//when aborted, reject, and don't append the out-dated new data to the list
deferred.reject();
}
}, 1000);
return {
promise: deferred.promise,
abort: function() {
//set isAborted flag to true so that the promise will be rejected, and no out-dated data will be appended to the list
isAborted = true;
}
};
}
$scope.doRefresh = function() {
//resets the flags and counters.
$scope.hasMore = true;
itemOffset = 0;
isRefreshing = true;
//aborts previous data fetcher
if(!!dataFetcher) dataFetcher.abort();
//triggers loadMore()
$scope.loadMore();
}
$scope.loadMore = function() {
//aborts previous data fetcher
if(!!dataFetcher) dataFetcher.abort();
//fetch new data
dataFetcher=fetchData(itemOffset, itemsPerPage);
dataFetcher.promise.then(function(list) {
if (isRefreshing) {
//clear isRefreshing flag
isRefreshing = false;
//empty the list (delete old data) before appending new data to the end of the list.
$scope.list.splice(0);
//hide the spin
$scope.$broadcast('scroll.refreshComplete');
}
//Check whether it has reached the end
if (list.length < itemsPerPage) $scope.hasMore = false;
//append new data to the list
$scope.list = $scope.list.concat(list);
//hides the spin
$scope.$broadcast('scroll.infiniteScrollComplete');
//notify ion-content to resize after inner height has changed.
//so that it will trigger infinite scroll again if needed.
$timeout(function(){
$ionicScrollDelegate.$getByHandle('mainScroll').resize();
});
});
//update itemOffset
itemOffset += itemsPerPage;
};
});
The correct Javscript is as follows:
JiCtrls.controller('homeCtrl', ['$scope', '$timeout', '$ionicScrollDelegate', 'DbService', 'JsonService',
function ($scope, $timeout, $ionicScrollDelegate, DbService, JsonService) {
$scope.items = [];
$scope.hasMore = true;
loadData(0);
//下拉更新
$scope.loadNewContent = function () {
loadData(2);
};
//上拉更新
$scope.loadMoreContent = function () {
loadData(1);
};
function loadData(stateType) {
if ($scope.sql == undefined) {
$scope.sql = "select top 5 * from information”;
}
DbService.getData($scope.sql, '').success(function (data, status, headers, config) {
var convertData = JsonService.convertData(data);
if (stateType == 0) {
for (var i = 0; i < convertData.length; i++) {
$scope.items.push(convertData[i]);
}
}
else if (stateType == 1) {
// $scope.items = $scope.items.concat(convertData);
for (var i = 0; i < convertData.length; i++) {
$scope.items.push(convertData[i]);
}
$timeout(function () {
$scope.$broadcast('scroll.infiniteScrollComplete');
}, 500);
}
else {
for (var i = 0; i < convertData.length; i++) {
$scope.items.unshift(convertData[i]);
}
// Stop the ion-refresher from spinning
$timeout(function () {
$scope.$broadcast("scroll.refreshComplete");
}, 500);
}
$ionicScrollDelegate.resize();
if (convertData == null || convertData.length <= 0) {
$scope.hasmore = false;
}
}).error(function (errorData, errorStatus, errorHeaders, errorConfig) {
console.log(errorData);
});
}
}
]);

Vimeo drop uploader to click uploader

im using vimeo drop uploader on my site. i got the uploder from
https://github.com/websemantics/vimeo-upload
its working well when i drop the image. but i dont know how to on click to open uploder window..
the uploder dont have the file input its only have the div
this is html
<div class="progress">
<div id="progress" class="progress-bar progress-bar-striped active" role="progressbar" aria-valuenow="46" aria-valuemin="0" aria-valuemax="100" style="width: 0%">0%
</div>
</div>
<div id="drop_zone">Drop files here</div>
and they use this script
<script>
function handleFileSelect(evt) {
evt.stopPropagation();
evt.preventDefault();
var files = evt.dataTransfer.files; // FileList object.
var accessToken = document.getElementById("accessToken").value;
var upgrade_to_1080 = document.getElementById("upgrade_to_1080").checked;
// Set Video Data
var videoName = document.getElementById("videoName").value;
var videoDescription = document.getElementById("videoDescription").value;
// Clear the results div
var node = document.getElementById('results');
while (node.hasChildNodes()) node.removeChild(node.firstChild);
// Rest the progress bar
updateProgress(0);
var uploader = new MediaUploader({
file: files[0],
token: accessToken,
upgrade_to_1080: upgrade_to_1080,
videoData: {
name: (videoName > '') ? videoName : 'Default name',
description: (videoDescription > '') ? videoDescription : 'Default description'
},
onError: function(data) {
var errorResponse = JSON.parse(data);
message = errorResponse.error;
var element = document.createElement("div");
element.setAttribute('class', "alert alert-danger");
element.appendChild(document.createTextNode(message));
document.getElementById('results1').appendChild(element);
},
onProgress: function(data) {
updateProgress(data.loaded / data.total);
},
onComplete: function(videoId) {
var url = "https://vimeo.com/"+videoId;
document.getElementById("video").value = url;
//var a = document.createElement('a');
// a.appendChild(document.createTextNode(url));
// a.setAttribute('href',url);
//
// var element = document.createElement("div");
// element.setAttribute('class', "alert alert-success");
// element.appendChild(a);
//
// document.getElementById('results').appendChild(element);
}
});
uploader.upload();
}
/**
* Dragover handler to set the drop effect.
*/
function handleDragOver(evt) {
evt.stopPropagation();
evt.preventDefault();
evt.dataTransfer.dropEffect = 'copy';
}
/**
* Wire up drag & drop listeners once page loads
*/
document.addEventListener('DOMContentLoaded', function () {
var dropZone = document.getElementById('drop_zone');
dropZone.addEventListener('dragover', handleDragOver, false);
dropZone.addEventListener('drop', handleFileSelect, false);
});
var elem = document.getElementById('drop_zone');
if(elem && document.createEvent) {
var evt = document.createEvent("MouseEvents");
evt.initEvent("click", true, false);
elem.dispatchEvent(evt);
}
/**
* Updat progress bar.
*/
function updateProgress(progress) {
progress = Math.floor(progress * 100);
var element = document.getElementById('progress');
element.setAttribute('style', 'width:'+progress+'%');
element.innerHTML = progress+'%';
}
progress
</script>
Can you help me on this how to i upload an video on click..
Demo https://github.com/googledrive/cors-upload-sample
Thanks

youtube iframe API does not work on ipad and iphone

I was trying to recreate the multiple iframes example detailed here for a slideshow. It works flawlessly in all browsers, including desktop safari, except on iphone and ipad.
http://codepen.io/lakshminp/pen/mepIB
Js:
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
var players = {}
var YT_ready = (function() {
var onReady_funcs = [],
api_isReady = false;
return function(func, b_before) {
if (func === true) {
api_isReady = true;
for (var i = 0; i < onReady_funcs.length; i++) {
// Removes the first func from the array, and execute func
onReady_funcs.shift()();
}
}
else if (typeof func == "function") {
if (api_isReady) func();
else onReady_funcs[b_before ? "unshift" : "push"](func);
}
}
})();
function onYouTubeIframeAPIReady() {
jQuery(window).bind("load", function() {
YT_ready(true);
});
}
YT_ready(function() {
var identifier = "v9d09JLBVRc";
players[identifier] = new YT.Player(identifier, {
events: {
'onReady': onPlayerReady,
"onStateChange": createYTEvent(identifier)
}
});
});
function onPlayerReady(event) {
event.target.playVideo();
}
// Returns a function to enable multiple events
function createYTEvent(identifier) {
var player = players[identifier]; // Get cached player instance
return function (event) {
console.log(event.data);
}
}
HTML:
<div id="yt-container">
<iframe width="640" height="480" id="v9d09JLBVRc" class="media-youtube-player" src="//www.youtube.com/embed/v9d09JLBVRc?enablejsapi=1&autoplay=0" frameborder="0" allowfullscreen></iframe>
</div>
According to this
functions and parameters such as autoplay, playVideo(), loadVideoById() won't work in all mobile environments
and in your YTReady function, you load dynamically a video and for the moment that's not possible on iOS.
You can also try the YouTubeDemoPage and try to load another id and you will see that it can't be done.
You should also check this.