How to access the specific camera on mobile phone through html5 - android

When I use html5 'getUserMedia' API to access acamera on the android(4.0) phone, it comes out "front camera", but I want to open "back camera". Sample code:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<title>Html5 Mobile Carema</title>
<script src="js/jquery.js"></script>
<script>
$(document).ready(init);
function init() {
try {
window.URL = window.URL || window.webkitURL || window.msURL
|| window.oURL;
navigator.getUserMedia = navigator.getUserMedia
|| navigator.webkitGetUserMedia
|| navigator.mozGetUserMedia || navigator.msGetUserMedia;
navigator.getUserMedia({
video : true
}, successsCallback, errorCallback);
} catch (err) {
// Tries it with old spec of string syntax
navigator.getUserMedia('video', successsCallback, errorCallback);
}
$(":button").click(function() {
slap();
});
}
function slap() {
var video = $("#myVideo")[0];
var canvas = capture(video);
$("#result").empty();
$("#result").append(canvas);
//alert();
var imgData = canvas.toDataURL('image/png;base64,');
//var imgData = canvas.toDataURL("image/png");
var imgData = imgData.substring(22);
//blb = dataURItoBlob(imgData);
//sendMsg(blb);
}
function errorCallback(err) {
}
function successsCallback(stream) {
$("#myVideo").attr("src", window.webkitURL.createObjectURL(stream));
}
function capture(video) {
var canvas = document.createElement('canvas');
var width = video.videoWidth;
var height = video.videoHeight;
canvas.width = video.videoWidth;
canvas.height = video.videoHeight;
var context = canvas.getContext('2d');
context.drawImage(video, 0, 0, 160, 120);
return canvas;
}
</script>
</head>
<body>
<video id="myVideo" autoplay="autoplay"></video>
<br> <input type="button" value="capture" />
<br><div id="result" style="width: 145px"></div>
<div>
<p id="resultMsg" style="color: red"></p>
<p id="decodeTime" style="color: green"></p>
</div>
</body>
</html>
I don't know how to access specific camera on android phone, anyone who knows? thanks

There is now the ability to specify a camera in the latest specification with the facingMode property: http://www.w3.org/TR/mediacapture-streams/#idl-def-VideoFacingModeEnum
This property is an optional part of the MediaStreamConstraints object that is the first argument of the getUserMedia method.
Here's a simplified example from the spec:
var supports = navigator.mediaDevices.getSupportedConstraints();
if (!supports["facingMode"]) {
// Handle lack of browser support if necessary
}
var gotten = navigator.mediaDevices.getUserMedia({
video: {
facingMode: {exact: "environment"}
}
});
The value environment means the back camera of the device. Other values are user, left and right.
Note that support for this varies depending on the browser/browser version.

See function gotSources(sourceInfos) in the code below
<!--
Based on Motion Detector Demo Created by Ákos Nikházy.
If you use this app please link this demo http://motion-detector.nikhazy-dizajn.hu/
-->
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>Frame capture demo</title>
</head>
<body>
<header>
<h1>Motion Detection</h1>
<h4>with HTML5 API using .getUserMedia()</h4>
</header>
<video autoplay></video>
<hr>
<canvas id="savePhoto"></canvas>
<script>
function hasGetUserMedia() {
//returns true if supported
return !!(navigator.getUserMedia || navigator.webkitGetUserMedia
|| navigator.mozGetUserMedia || navigator.msGetUserMedia);
}
function onSuccess(stream) {
//If we can stream from camera.
var source;
//Get the stream. This goes to the video tag
if (window.URL) {
source = window.URL.createObjectURL(stream);
} else if (window.webkitURL) {
source = window.webkitURL.createObjectURL(stream);
} else {
source = stream; // Opera and Firefox
}
//Set up video tag
video.autoplay = true;
video.src = source;
//We try to find motion in every X second
setInterval(function() {
motionDetector();
}, sampling);
}
function onError() {
//if we fail (not supported, no camera etc.)
alert('No stream, no win. Refresh.');
}
function saveImage(canvasToSave) {
//create image from canvas
dataUrl = canvasToSave.toDataURL();
imageFound = document.createElement('img');
imageFound.src = dataUrl;
document.body.appendChild(imageFound);
}
function motionDetector() {
ctxSave.drawImage(video, 0, 0, savePhoto.width, savePhoto.height);
}
/*After all those functions lets start setting up the program*/
//Set up elements. Should be a ini() but I don't care right now
var video = document.querySelector('video'); //the video tag
var savePhoto = document.getElementById('savePhoto'); //the possible saved image's canvas
var ctxSave = savePhoto.getContext('2d'); //the latest image from video in full size and color
var sampling = 1000; //how much time needed between samples in milliseconds
var videoSourceInfo = null;
//We need this so we can use the videoWidth and ...Height, also we setup canvas sizes here, after we have video data
video.addEventListener("loadedmetadata", function() {
console.log(video.videoWidth + ":" + video.videoHeight)
savePhoto.width = video.videoWidth;
savePhoto.height = video.videoHeight;
});
function start() { //Start the whole magic
if (hasGetUserMedia()) {
//it is working?
navigator.getUserMedia
|| (navigator.getUserMedia = navigator.mozGetUserMedia
|| navigator.webkitGetUserMedia
|| navigator.msGetUserMedia);
var videoSourceInfoId = videoSourceInfo.id;
var constraints = {
video : {
optional: [{sourceId: videoSourceInfoId}]
},
toString : function() {
return "video";
}
};
navigator.getUserMedia(constraints, onSuccess, onError);
} else {
//no support
alert('getUserMedia() is not supported in your browser. Try Chrome.');
}
}
function gotSources(sourceInfos) {
for (var i = sourceInfos.length-1 ; i >= 0; i--) { // get last camera index (supposed to back camera)
var sourceInfo = sourceInfos[i];
if (sourceInfo.kind === 'video') {
videoSourceInfo = sourceInfo;
console.log('SourceId: ', videoSourceInfo.id);
start();
break;
} else {
console.log('Some other kind of source: ', sourceInfo);
}
}
}
if (typeof MediaStreamTrack === 'undefined') {
alert('This browser does not support MediaStreamTrack.\n\nTry Chrome Canary.');
} else {
MediaStreamTrack.getSources(gotSources); // async task
}
</script>
</body>
</html>

Hi I think this works with you
<script>
var gum = mode =>
navigator.mediaDevices.getUserMedia({video: {facingMode: {exact: mode}}})
.then(stream => (video.srcObject = stream))
.catch(e => log(e));
var stop = () => video.srcObject && video.srcObject.getTracks().forEach(t => t.stop());
var log = msg => div.innerHTML += msg + "<br>";
</script>
<button onclick="stop();gum('user')">Front</button>
<button onclick="stop();gum('environment')">Back</button>
<div id="div"></div><br>
<video id="video" height="320" autoplay></video>
<script src="https://webrtc.github.io/adapter/adapter-latest.js"></script>
facingMode??
https://github.com/webrtcHacks/adapter/issues/820
https://developer.mozilla.org/en-US/docs/Web/API/MediaTrackConstraints/facingMode

Related

Youtube iframe failed to load in Android

I am trying to play YouTube Videos on android devices using webview and youtube iframe api. While testing the same on 4.2 devices, it did work on 4.2.2 Nexus 4. But when I tried it on Sony Xpedia L, its showing the buffering status, but the video never gets loaded (Screen Shots attached). What could be a fix for this? Any suggestions...?!?!
My code is as follows..
JAVA CODE
wvVideo = (WebView)findViewById(R.id.wvVideo);
wvVideo.setWebChromeClient(new WebChromeClient());
WebSettings webSettings = wvVideo.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setMediaPlaybackRequiresUserGesture(false);
wvVideo.addJavascriptInterface(new WebAppInterface(this), "Android");
wvVideo.loadUrl("http://test.com/iframeYouTube.html?videoid="+videoURL);
wvVideo.loadUrl("javascript:playVideo();");
XML
<WebView
android:id="#+id/wvVideo"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_centerInParent="true"
android:background="#212121"></WebView>
HTML
<!DOCTYPE html>
<html style="height:100%;margin:0;padding:0;width:100%">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body style="background:#212121;height:100%;margin:0;padding:0">
<!-- 1. The <iframe> (and video player) will replace this <div> tag. -->
<div id="player" style="margin:0;padding:0"></div>
<script>
var Query = function () {
var query_string = {};
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
if (typeof query_string[pair[0]] === "undefined") {
query_string[pair[0]] = pair[1];
} else if (typeof query_string[pair[0]] === "string") {
var arr = [ query_string[pair[0]], pair[1] ];
query_string[pair[0]] = arr;
} else {
query_string[pair[0]].push(pair[1]);
}
}
return query_string;
} ();
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 player;
function onYouTubeIframeAPIReady() {
player = new YT.Player('player', {
height:'100%',width:'100%',
videoId: Query.videoid,
playerVars: { 'autoplay': 0, 'controls': 0, 'showinfo':0, 'modestbranding':1},
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
function onPlayerReady(event) {
cueCheck();
timerFunction();
videoLength();
}
var done = false;
function onPlayerStateChange(event) {
Android.playState(event.data+"");
if (event.data == YT.PlayerState.PLAYING && !done) {
done = true;
}
}
function cueCheck()
{
Android.playState("cued");
}
function timerFunction(){
console.log("function");
Android.updateTimer(player.getCurrentTime()+"");
setTimeout(timerFunction, 20);
}
function videoLength(){
Android.getVideoLength(player.getDuration()+"");
}
function seekTo(val) {
player.seekTo(val);
// player.playVideo();
}
function pauseVideo(){
player.pauseVideo()
}
function playVideo(){
player.playVideo()
}
</script>
</body>
</html>
String html = getHTML(url);
MainActivity.webview.getSettings().setJavaScriptEnabled(true);
MainActivity.webview.getSettings().setPluginState(PluginState.ON);
final String mimeType = "text/html";
final String encoding = "UTF-8";
MainActivity.webview.setWebViewClient(new WebViewClient());
MainActivity.webview.setWebChromeClient(new WebChromeClient());
webview.loadDataWithBaseURL("", html, mimeType,
encoding, "");
public static String getHTML(String str) {
String html = "<iframe class=\"youtube-player\" style=\"overflow:hidden; width: 100%; height: 95%; scrolling=\"no\" padding:0px; margin:0px\" id=\"ytplayer\" type=\"text/html\" src=\"http://www.youtube.com/embed/"
+ str
+ "?html5=1&autoplay=1 & fs=0\" frameborder=\"0\" >\n"
+ "</iframe>\n ";
return html;
}
I faced with the same issue and the only thing that i can say is that the error is related with the Android version. Particularly, as I posted here :
In Android 4 versions, can't autoplay. The user has to press play button into the iframe to start play the video. Particularly:
In Android 4.1 it reproduces the audio but not the image.
In Android 4.3 i tested in devices which can reproduce audio but no
video and devices that can't reproduce anything.
In Android 4.4 don't reproduce anything
From Android 5 and + everything works fine.
I spend so many time trying to do it i don't find the way :(

Phonegap upload error code 3

I'm developing a PhoneGap app with file upload and I'm using the following script which when I tap on upload picture it gives me an error Upload failed Code=3.
<!DOCTYPE HTML>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, maximum-scale=1.0, user-scalable=no;" />
<meta http-equiv="Content-type" content="text/html; charset=utf-8">
<title>PhoneGap</title>
<style type="text/css">
div {border: 1px solid black;}
input {width: 100%;}
</style>
<script src="cordova-2.5.0.js"></script>
<script type="text/javascript" charset="utf-8">
var options = new FileUploadOptions();
options.headers = {
Connection: "close"
}
options.chunkedMode = false;
var deviceReady = false;
/**
* Take picture with camera
*/
function takePicture() {
navigator.camera.getPicture(
function(uri) {
var img = document.getElementById('camera_image');
img.style.visibility = "visible";
img.style.display = "block";
img.src = uri;
document.getElementById('camera_status').innerHTML = "Success";
},
function(e) {
console.log("Error getting picture: " + e);
document.getElementById('camera_status').innerHTML = "Error getting picture.";
},
{ quality: 50, destinationType: navigator.camera.DestinationType.FILE_URI});
};
/**
* Select picture from library
*/
function selectPicture() {
navigator.camera.getPicture(
function(uri) {
var img = document.getElementById('camera_image');
img.style.visibility = "visible";
img.style.display = "block";
img.src = uri;
document.getElementById('camera_status').innerHTML = "Success";
},
function(e) {
console.log("Error getting picture: " + e);
document.getElementById('camera_status').innerHTML = "Error getting picture.";
},
{ quality: 50, destinationType: navigator.camera.DestinationType.FILE_URI, sourceType: navigator.camera.PictureSourceType.PHOTOLIBRARY});
};
/**
* Upload current picture
*/
function uploadPicture() {
// Get URI of picture to upload
var img = document.getElementById('camera_image');
var imageURI = img.src;
if (!imageURI || (img.style.display == "none")) {
document.getElementById('camera_status').innerHTML = "Take picture or select picture from library first.";
return;
}
// Verify server has been entered
server = document.getElementById('serverUrl').value;
if (server) {
// Specify transfer options
var options = new FileUploadOptions();
options.fileKey="file";
options.fileName=imageURI.substr(imageURI.lastIndexOf('/')+1);
options.mimeType="image/jpeg";
options.chunkedMode = false;
// Transfer picture to server
var ft = new FileTransfer();
ft.upload(imageURI, server, function(r) {
document.getElementById('camera_status').innerHTML = "Upload successful: "+r.bytesSent+" bytes uploaded.";
}, function(error) {
document.getElementById('camera_status').innerHTML = "Upload failed: Code = "+error.code;
}, options);
}
}
/**
* View pictures uploaded to the server
*/
function viewUploadedPictures() {
// Get server URL
server = document.getElementById('serverUrl').value;
if (server) {
// Get HTML that lists all pictures on server using XHR
var xmlhttp = new XMLHttpRequest();
// Callback function when XMLHttpRequest is ready
xmlhttp.onreadystatechange=function(){
if(xmlhttp.readyState === 4){
// HTML is returned, which has pictures to display
if (xmlhttp.status === 200) {
document.getElementById('server_images').innerHTML = xmlhttp.responseText;
}
// If error
else {
document.getElementById('server_images').innerHTML = "Error retrieving pictures from server.";
}
}
};
xmlhttp.open("GET", server , true);
xmlhttp.send();
}
}
/**
* Function called when page has finished loading.
*/
function init() {
document.addEventListener("deviceready", function() {deviceReady = true;}, false);
window.setTimeout(function() {
if (!deviceReady) {
alert("Error: PhoneGap did not initialize. Demo will not run correctly.");
}
},2000);
}
</script>
</head>
<body onload="init();">
<h3>PhoneGap Camera Upload Demo</h3>
<div>
<h3>Server URL for upload.php:</h3>
<input id="serverUrl" type="text" value="http://usersamplesite.com/folder" />
</div>
<br/>
<!-- Camera -->
<div>
<h3>Camera:</h3>
<b>Status:</b> <span id="camera_status"></span><br>
<b>Image:</b> <img style="width:120px;visibility:hidden;display:none;" id="camera_image" src="" />
</div>
<!-- Actions -->
<div>
<input type="button" onclick="takePicture();" value="Take Picture" /><br/>
<input type="button" onclick="selectPicture();" value="Select Picture from Library" /><br/>
<input type="button" onclick="uploadPicture();" value="Upload Picture" />
</div>
<br/>
<!-- Server pictures -->
<div>
<h3>Server:</h3>
<b>Images on server:</b>
<div id="server_images"></div>
</div>
<!-- Actions -->
<div>
<input type="button" onclick="viewUploadedPictures();" value="View Uploaded Pictures" />
</div>
</body>
</html>
I found out here that, I should use the below script to make it work, but I don't know where to put it in the script and I need help, I'm new to PhoneGap.
options.headers = {
Connection: "close"
}
options.chunkedMode = false;
Add true in as last param of Upload Function
upload(filePath, server, successCallback, errorCallback, options, true);
Try putting options.header inside uploadPicture() rather than putting it at start of your document.
function uploadPicture() {
......
......
if(server) {
// Specify transfer options
var options = new FileUploadOptions();
options.fileKey="file";
options.fileName=imageURI.substr(imageURI.lastIndexOf('/')+1);
options.mimeType="image/jpeg";
options.headers = {
Connection: "close"
}
options.chunkedMode = false;
// Transfer picture to server
var ft = new FileTransfer();
ft.upload(imageURI, server, success, failure, options, true);
}
}

Login with Twitter on phonegap app

I'm trying to implement the login action using the twitter acount in my cordova app.
I have found a script using Childbrowser.js file to do it but it's not supported anymore so that I am trying to do it using the inappBrowser plugin instead of the childbrowser.
I succeeded in opening the login interface but after the login it redirect me to a web page. How can I redirect to my html local page? can I get ignore the redirect url and just get the access token?
this is the code that I am using:
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no;" />
<meta charset="utf-8">
<script type="text/javascript" charset="utf-8" src="cordova.js"></script>
<script type="text/javascript" charset="utf-8" src="js/jquery-2.1.1.js"></script>
<script type="text/javascript" charset="utf-8" src="js/codebird.js"></script>
<script type="text/javascript" charset="utf-8" src="js/jsOAuth-1.3.1.js"></script>
<script type="text/javascript">
function onBodyLoad(){
document.addEventListener("deviceready", onDeviceReady, false);
}
function onDeviceReady() {
var root = this;
//var cb = new Codebird;
var cb = window.open();
if(!localStorage.getItem(twitterKey)){
$("#loginBtn").show();
$("#logoutBtn").hide();
}
else {
return ('here test');
$("#loginBtn").hide();
$("#logoutBtn").show();
}
if (cb != null) {
cb.addEventListener('loadstart', function(event) { onOpenExternal(); });
cb.addEventListener('loadstop', function(event) { onOpenExternal();});
cb.addEventListener('exit', function(event) { onCloseBrowser() });
}
}
function onCloseBrowser() {
alert('onCloseBrowser');
console.log("onCloseBrowser!");
}
function locChanged(loc) {
alert('locChanged');
console.log("locChanged!");
}
function onOpenExternal() {
alert('onOpenExternal');
console.log("onOpenExternal!");
}
</script>
<!--Below is the code for twitter-->
<script>
// GLOBAL VARS
var oauth; // It Holds the oAuth data request
var requestParams; // Specific param related to request
var options = {
consumerKey: 'xxxxx', // YOUR Twitter CONSUMER_KEY
consumerSecret: 'xxxxxx', // YOUR Twitter CONSUMER_SECRET
callbackUrl: "http://127.0.0.1:81/" }; // YOU have to replace it on one more Place
var twitterKey = "twtrKey"; // This key is used for storing Information related
var Twitter = {
init:function(){
// Apps storedAccessData , Apps Data in Raw format
var storedAccessData, rawData = localStorage.getItem(twitterKey);
// here we are going to check whether the data about user is already with us.
if(localStorage.getItem(twitterKey) !== null){
// when App already knows data
storedAccessData = JSON.parse(rawData); //JSON parsing
//options.accessTokenKey = storedAccessData.accessTokenKey; // data will be saved when user first time signin
options.accessTokenSecret = storedAccessData.accessTokenSecret; // data will be saved when user first first signin
// javascript OAuth take care of everything for app we need to provide just the options
oauth = OAuth(options);
oauth.get('https://api.twitter.com/1/account/verify_credentials.json?skip_status=true',
function(data) {
var entry = JSON.parse(data.text);
console.log("USERNAME: " + entry.screen_name);
}
);
}
else {
// we have no data for save user
oauth = OAuth(options);
oauth.get('https://api.twitter.com/oauth/request_token',
function(data) {
requestParams = data.text;
cb=window.open('https://api.twitter.com/oauth/authorize?'+data.text); // This opens the Twitter authorization / sign in page
cb.addEventListener('loadstop', function(loc){alert('stop: ' + loc.url);
// Twitter.success(loc);
});
},
function(data) {
console.log("ERROR: "+data);
}
);
}
},
/*
When ChildBrowser's URL changes we will track it here.
We will also be acknowledged was the request is a successful or unsuccessful
*/
success:function(loc){
alert('ok entred');
// Here the URL of supplied callback will Load
/*
Here Plugin will check whether the callback Url matches with the given Url
*/
if (loc.indexOf("http://127.0.0.1:81/?") >= 0) {
// Parse the returned URL
var index, verifier = '';
var params = loc.substr(loc.indexOf('?') + 1);
params = params.split('&');
for (var i = 0; i < params.length; i++) {
var y = params[i].split('=');
if(y[0] === 'oauth_verifier') {
verifier = y[1];
}
}
// Here we are going to change token for request with token for access
/*
Once user has authorised us then we have to change the token for request with token of access
here we will give data to localStorage.
*/
oauth.get('https://api.twitter.com/oauth/access_token?oauth_verifier='+verifier+'&'+requestParams,
function(data) {
var accessParams = {};
var qvars_tmp = data.text.split('&');
for (var i = 0; i < qvars_tmp.length; i++) {
var y = qvars_tmp[i].split('=');
accessParams[y[0]] = decodeURIComponent(y[1]);
}
$('#oauthStatus').html('<span style="color:green;">Success!</span>');
$('#stage-auth').hide();
$('#stage-data').show();
oauth.setAccessToken([accessParams.oauth_token, accessParams.oauth_token_secret]);
// Saving token of access in Local_Storage
var accessData = {};
accessData.accessTokenKey = accessParams.oauth_token;
accessData.accessTokenSecret = accessParams.oauth_token_secret;
// Configuring Apps LOCAL_STORAGE
console.log("TWITTER: Storing token key/secret in localStorage");
localStorage.setItem(twitterKey, JSON.stringify(accessData));
oauth.get('https://api.twitter.com/1/account/verify_credentials.json?skip_status=true',
function(data) {
var entry = JSON.parse(data.text);
console.log("TWITTER USER: "+entry.screen_name);
$("#welcome").show();
document.getElementById("welcome").innerHTML="welcome " + entry.screen_name;
successfulLogin();
// Just for eg.
app.init();
},
function(data) {
console.log("ERROR: " + data);
}
);
// Now we have to close the child browser because everthing goes on track.
window.plugins.childBrowser.close();
},
function(data) {
alert('rr');
console.log(data);
}
);
}
else {
// Just Empty
}
},
tweet:function(){
var storedAccessData, rawData = localStorage.getItem(twitterKey);
storedAccessData = JSON.parse(rawData); // Paring Json
options.accessTokenKey = storedAccessData.accessTokenKey; // it will be saved on first signin
options.accessTokenSecret = storedAccessData.accessTokenSecret; // it will be save on first login
// javascript OAuth will care of else for app we need to send only the options
oauth = OAuth(options);
oauth.get('https://api.twitter.com/1/account/verify_credentials.json?skip_status=true',
function(data) {
var entry = JSON.parse(data.text);
Twitter.post();
}
);
},
/*
We now have the data to tweet
*/
post:function(){
var theTweet = $("#tweet").val(); // You can change it with what else you likes.
oauth.post('https://api.twitter.com/1/statuses/update.json',
{ 'status' : theTweet, // javascript OAuth encodes this
'trim_user' : 'true' },
function(data) {
var entry = JSON.parse(data.text);
console.log(entry);
// just for eg.
done();
},
function(data) {
console.log(data);
}
);
}
}
function done(){
$("#tweet").val('');
}
function successfulLogin(){
$("#loginBtn").hide();
$("#logoutBtn,#tweet,#tweeter,#tweetBtn,#tweetText").show();
}
function logOut(){
//localStorage.clear();
window.localStorage.removeItem(twitterKey);
document.getElementById("welcome").innerHTML="Please Login to use this app";
$("#loginBtn").show();
$("#logoutBtn,#tweet,#tweeter,#tweetText,#tweetBtn").hide();
}
</script>
<!--Code for Twitter ends here-->
</head>
<body onload="onBodyLoad()">
<h4>Oodles Twitter App</h4>
<table border="1">
<tr>
<th>Login using Twitter</th>
<th>
<button id="loginBtn" onclick="Twitter.init()">Login</button>
<button id="logoutBtn" onclick="logOut();">Logout</button>
</th>
</tr>
<tr id="tweetText" style="display:none;">
<td colspan="2"><textarea id="tweet" style="display:none;"></textarea></td>
</tr>
<tr id="tweetBtn" style="display:none;">
<td colspan="2" align="right">
<button id="tweeter" onclick="Twitter.tweet();" style="display:none">Tweet</button>
</td>
</tr>
<tr><td colspan="2"><div id="welcome">Please Login to use this app</div></td></tr>
</table>
</body>
Actually there is error in your code you have to fix it:
the https://api.twitter.com/1/account/verify_credentials.json?skip_status=true' is no more used change it to 1.1.
also change the way you close your inappbrowser.
this code works for me try it:
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no;" />
<meta charset="utf-8">
<script type="text/javascript" charset="utf-8" src="cordova.js"></script>
<script type="text/javascript" charset="utf-8" src="js/jquery-2.1.1.js"></script>
<script type="text/javascript" charset="utf-8" src="js/codebird.js"></script>
<script type="text/javascript" charset="utf-8" src="js/jsOAuth-1.3.1.js"></script>
<script type="text/javascript">
function onBodyLoad(){
document.addEventListener("deviceready", onDeviceReady, false);
}
function onDeviceReady() {
var root = this;
//var cb = new Codebird;
var cb = window.open();
if(!localStorage.getItem(twitterKey)){
$("#loginBtn").show();
$("#logoutBtn").hide();
}
else {
retiurn ('hhhh');
$("#loginBtn").hide();
$("#logoutBtn").show();
}
if (cb != null) {
cb.addEventListener('loadstart', function(event) { onOpenExternal(); });
cb.addEventListener('loadstop', function(event) { onOpenExternal();});
cb.addEventListener('exit', function(event) { onCloseBrowser() });
}
}
function onCloseBrowser() {
alert('onCloseBrowser');
console.log("onCloseBrowser!");
}
function locChanged(loc) {
alert('locChanged');
console.log("locChanged!");
}
function onOpenExternal() {
alert('onOpenExternal');
console.log("onOpenExternal!");
}
</script>
<!--Below is the code for twitter-->
<script>
// GLOBAL VARS
var oauth; // It Holds the oAuth data request
var requestParams; // Specific param related to request
var options = {
consumerKey: 'xxxxx', // YOUR Twitter CONSUMER_KEY
consumerSecret: 'xxxxx', // YOUR Twitter CONSUMER_SECRET
callbackUrl: "http://127.0.0.1:81/" }; // YOU have to replace it on one more Place
var twitterKey = "twtrKey"; // This key is used for storing Information related
var Twitter = {
init:function(){
// Apps storedAccessData , Apps Data in Raw format
var storedAccessData, rawData = localStorage.getItem(twitterKey);
// here we are going to check whether the data about user is already with us.
if(localStorage.getItem(twitterKey) !== null){
// when App already knows data
storedAccessData = JSON.parse(rawData); //JSON parsing
//options.accessTokenKey = storedAccessData.accessTokenKey; // data will be saved when user first time signin
options.accessTokenSecret = storedAccessData.accessTokenSecret; // data will be saved when user first first signin
// javascript OAuth take care of everything for app we need to provide just the options
oauth = OAuth(options);
oauth.get('https://api.twitter.com/1/account/verify_credentials.json?skip_status=true',
function(data) {
var entry = JSON.parse(data.text);
console.log("USERNAME: " + entry.screen_name);
}
);
}
else {
// we have no data for save user
oauth = OAuth(options);
oauth.get('https://api.twitter.com/oauth/request_token',
function(data) {
requestParams = data.text;
cb=window.open('https://api.twitter.com/oauth/authorize?'+data.text,'_blank', 'location=no'); // This opens the Twitter authorization / sign in page
cb.addEventListener('loadstop', function(loc){//alert('stop: ' + loc.url);
Twitter.success(loc);
});
},
function(data) {
console.log("ERROR: "+data);
}
);
}
},
/*
When ChildBrowser's URL changes we will track it here.
We will also be acknowledged was the request is a successful or unsuccessful
*/
success:function(loc){
// alert(loc.url);
// Here the URL of supplied callback will Load
/*
Here Plugin will check whether the callback Url matches with the given Url
*/
if (loc.url.indexOf("http://127.0.0.1:81/?") >-1) {
// Parse the returned URL
var index, verifier = '';
var params = loc.url.substr(loc.url.indexOf('?') + 1);
params = params.split('&');
for (var i = 0; i < params.length; i++) {
var y = params[i].split('=');
if(y[0] === 'oauth_verifier') {
verifier = y[1];
}
}
// Here we are going to change token for request with token for access
/*
Once user has authorised us then we have to change the token for request with token of access
here we will give data to localStorage.
*/
oauth.get('https://api.twitter.com/oauth/access_token?oauth_verifier='+verifier+'&'+requestParams,
function(data) {
var accessParams = {};
var qvars_tmp = data.text.split('&');
for (var i = 0; i < qvars_tmp.length; i++) {
var y = qvars_tmp[i].split('=');
accessParams[y[0]] = decodeURIComponent(y[1]);
}
// alert(verifier)
$('#oauthStatus').html('<span style="color:green;">Success!</span>');
$('#stage-auth').hide();
$('#stage-data').show();
oauth.setAccessToken([accessParams.oauth_token, accessParams.oauth_token_secret]);
// Saving token of access in Local_Storage
var accessData = {};
accessData.accessTokenKey = accessParams.oauth_token;
accessData.accessTokenSecret = accessParams.oauth_token_secret;
// Configuring Apps LOCAL_STORAGE
console.log("TWITTER: Storing token key/secret in localStorage");
localStorage.setItem(twitterKey, JSON.stringify(accessData));
oauth.get('https://api.twitter.com/1.1/account/verify_credentials.json?skip_status=true',
function(data) {
// alert('key'+twitterKey);
var entry = JSON.parse(data.text);
console.log("TWITTER USER: "+entry.screen_name);
$("#welcome").show();
document.getElementById("welcome").innerHTML="welcome " + entry.screen_name;
successfulLogin();
// Just for eg.
app.init();
},
function(data) {
console.log("ERROR: " + data);
}
);
// Now we have to close the child browser because everthing goes on track.
cb.close();
},
function(data) {
// alert('rr');
console.log(data);
}
);
}
else {
// Just Empty
}
},
tweet:function(){
var storedAccessData, rawData = localStorage.getItem(twitterKey);
storedAccessData = JSON.parse(rawData); // Paring Json
options.accessTokenKey = storedAccessData.accessTokenKey; // it will be saved on first signin
options.accessTokenSecret = storedAccessData.accessTokenSecret; // it will be save on first login
// javascript OAuth will care of else for app we need to send only the options
oauth = OAuth(options);
oauth.get('https://api.twitter.com/1.1/account/verify_credentials.json?skip_status=true',
function(data) {
var entry = JSON.parse(data.text);
Twitter.post();
}
);
},
/*
We now have the data to tweet
*/
post:function(){
var theTweet = $("#tweet").val(); // You can change it with what else you likes.
oauth.post('https://api.twitter.com/1.1/statuses/update.json',
{ 'status' : theTweet, // javascript OAuth encodes this
'trim_user' : 'true' },
function(data) {
var entry = JSON.parse(data.text);
console.log(entry);
// just for eg.
done();
},
function(data) {
console.log(data);
}
);
}
}
function done(){
$("#tweet").val('');
}
function successfulLogin(){
$("#loginBtn").hide();
$("#logoutBtn,#tweet,#tweeter,#tweetBtn,#tweetText").show();
}
function logOut(){
//localStorage.clear();
window.localStorage.removeItem(twitterKey);
document.getElementById("welcome").innerHTML="Please Login to use this app";
$("#loginBtn").show();
$("#logoutBtn,#tweet,#tweeter,#tweetText,#tweetBtn").hide();
}
</script>
<!--Code for Twitter ends here-->
</head>
<body onload="onBodyLoad()">
<h4>Oodles Twitter App</h4>
<table border="1">
<tr>
<th>Login using Twitter</th>
<th>
<button id="loginBtn" onclick="Twitter.init()">Login</button>
<button id="logoutBtn" onclick="logOut();">Logout</button>
</th>
</tr>
<tr id="tweetText" style="display:none;">
<td colspan="2"><textarea id="tweet" style="display:none;"></textarea></td>
</tr>
<tr id="tweetBtn" style="display:none;">
<td colspan="2" align="right">
<button id="tweeter" onclick="Twitter.tweet();" style="display:none">Tweet</button>
</td>
</tr>
<tr><td colspan="2"><div id="welcome">Please Login to use this app</div></td></tr>
</table>
</body>

Onclick with 2 tasks

I'm trying to do 2 things at once with OnClick and don't know if I'm coding it wrong or if it's not possible. I'm trying to click on an image and using onclick go to another image while also playing a sound and then back to the original image. I have 3 examples in a row. The first example goes from image1 to image2 and back to image 1 without playing a sound. The 2nd example goes from image1 to image2 to image3 and back to image 1 without playing a sound. The third example plays a sound Onclick but its not going to image2. I want it to play a sound and also go to image2 when I click. Can anyone help?
http://readautism.atwebpages.com/index3.html
<!doctype html>
<html>
<head>
<meta charset="ISO-8859-1" />
<title>Example of How to Play a Sound on Click or on MouseOver</title>
<script>
var html5_audiotypes={ //define list of audio file extensions and their associated audio types. Add to it if your specified audio file isn't on this list:
"mp3": "audio/mpeg",
"mp4": "audio/mp4",
"ogg": "audio/ogg",
"wav": "audio/wav"
}
function createsoundbite(sound){
var html5audio=document.createElement('audio')
if (html5audio.canPlayType){ //check support for HTML5 audio
for (var i=0; i<arguments.length; i++){
var sourceel=document.createElement('source')
sourceel.setAttribute('src', arguments[i])
if (arguments[i].match(/\.(\w+)$/i))
sourceel.setAttribute('type', html5_audiotypes[RegExp.$1])
html5audio.appendChild(sourceel)
}
html5audio.load()
html5audio.playclip=function(){
html5audio.pause()
html5audio.currentTime=0
html5audio.play()
}
return html5audio
}
else{
return {playclip:function(){throw new Error("Your browser doesn't support HTML5 audio unfortunately")}}
}
}
//Initialize two sound clips with 1 fallback file each:
var mouseoversound=createsoundbite("whistle.ogg", "whistle.mp3")
var clicksound=createsoundbite('http://static.sfdict.com/staticrep/dictaudio/P05/P0501900.mp3', "whistle.ogg")
var uniquevar=createsoundbite("pizza.wav", "whistle.ogg", "whistle.mp3")
</script>
<script>
var gStorage = {};
function toogle(anImage, anAltSrcArr) {
if (typeof(anImage) === "undefined" || typeof(anAltSrcArr) === "undefined" || anAltSrcArr.length === 0) {
return;
}
var id = anImage.id;
var oldSrc = anImage.src;
if (typeof(gStorage[id]) === "undefined") {
gStorage[id] = {
'id': id,
'origSrc': oldSrc,
'i': 0
};
}
gStorage[id].i += 1;
if (gStorage[id].i > anAltSrcArr.length) {
gStorage[id].i = 0;
}
if (gStorage[id].i === 0) {
anImage.src = gStorage[id].origSrc;
} else {
anImage.src = anAltSrcArr[gStorage[id].i - 1];
}
}
</script>
</head>
<body
<p>Click on an image</p>
<img class="with-action" id="image1" name="image1" src="http://dummyimage.com/50/f00/fff&text=a" onclick='toogle(this, ["http://dummyimage.com/50/ab0/fff&text=b"]);' />
<img class="with-action" id="image2" name="image2" src="http://dummyimage.com/50/0f0/fff&text=a" onclick='toogle(this, ["http://dummyimage.com/50/0fa/fff&text=b", "http://dummyimage.com/50/0bb/fff&text=c"]);'/>
<img class="with-action" id="image3" name="image3" src="http://dummyimage.com/50/00f/fff&text=a" onclick="uniquevar.playclip()";'toogle(this, ["http://dummyimage.com/50/ab0/fff&text=b"])'; />
</body>
</html>
Try
<img class="with-action" id="image3" name="image3" src="http://dummyimage.com/50/0bb/fff&text=c" onclick="uniquevar.playclip();toogle(this, ['http://dummyimage.com/50/0fa/fff&text=b', 'http://dummyimage.com/50/0bb/fff&text=c']);">
Single and double quotes mix-up, apparent due to syntax-highlighting in the snippet that you posted.

Hide URL in browser on Android 2.3 using HTML/javascript

Does somebody know how to hide URL on Android (like full screen) using HTML/javascript?
On iPad (Safari) this is simple and can be done using only a few meta tags.
I have tried something like that:
$(document).ready(function () {
scrollTo(0, 1);
});
But, on Motorola T1, the URL bar is still displayed :(
None of any solution above worked for me on Samsung S3 mini phone with Android 4.1.1
But I have followed the mentioned url and there was the absolutely right solution.
Thanks for it.
https://gist.github.com/1183357
See Fresheyeball's implementation. That works perfectly in portrait and landscape mode as well.
I just copy here my full example:
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<script type="text/javascript" src="jquery-1.8.3.min.js"></script>
<script type="text/javascript">
$(function() {
hideAddressBar();
});
function hideAddressBar() {
if (navigator.userAgent.match(/Android/i)) {
window.scrollTo(0, 0); // reset in case prev not scrolled
var nPageH = $(document).height();
var nViewH = window.outerHeight;
if (nViewH > nPageH) {
nViewH = nViewH / window.devicePixelRatio;
$('BODY').css('height', nViewH + 'px');
}
window.scrollTo(0, 1);
} else {
addEventListener("load", function() {
setTimeout(hideURLbar, 0);
setTimeout(hideURLbar, 500);
}, false);
}
function hideURLbar() {
if (!pageYOffset) {
window.scrollTo(0, 1);
}
}
return this;
}
</script>
</head>
<body>
<section>
<div>
<h1>First title</h1>
<p>Just some content</p>
</div>
</section>
<section>
<div>Any text</div>
</section>
</body>
</html>
Of course you need to put the jQuery main js file as well in order this example work properly. You can download from here http://jquery.com/download/
try this
$(document).ready(function() {
if (navigator.userAgent.match(/Android/i)) {
window.scrollTo(0,0); // reset in case prev not scrolled
var nPageH = $(document).height();
var nViewH = window.outerHeight;
if (nViewH > nPageH) {
nViewH -= 250;
$('BODY').css('height',nViewH + 'px');
}
window.scrollTo(0,1);
}
});
it works even if your page is not long enough
Try this one. I've used it and it seems to work perfectly on Android. It's from here:
https://gist.github.com/1183357
/*
* Normalized hide address bar for iOS & Android
* (c) Scott Jehl, scottjehl.com
* MIT License
*/
(function( win ){
var doc = win.document;
// If there's a hash, or addEventListener is undefined, stop here
if( !location.hash && win.addEventListener ){
//scroll to 1
window.scrollTo( 0, 1 );
var scrollTop = 1,
getScrollTop = function(){
return win.pageYOffset || doc.compatMode === "CSS1Compat" && doc.documentElement.scrollTop || doc.body.scrollTop || 0;
},
//reset to 0 on bodyready, if needed
bodycheck = setInterval(function(){
if( doc.body ){
clearInterval( bodycheck );
scrollTop = getScrollTop();
win.scrollTo( 0, scrollTop === 1 ? 0 : 1 );
}
}, 15 );
win.addEventListener( "load", function(){
setTimeout(function(){
//at load, if user hasn't scrolled more than 20 or so...
if( getScrollTop() < 20 ){
//reset to hide addr bar at onload
win.scrollTo( 0, scrollTop === 1 ? 0 : 1 );
}
}, 0);
} );
}
})( this );

Categories

Resources