window.location.replace wtih Phonegap - javascript

I try setup a JS function to auto load a index page in a different language, regardig the setting device o my reader.
I try with this...but don't work :
<script src="cordova-2.2.0.js"></script>
<script type="text/javascript" charset="utf-8">
function checkLanguage() {
if (navigator.globalization.getPreferredLanguage()='en_EN')
{
window.location.replace("index_en.html");
}
else if (navigator.globalization.getPreferredLanguage()='fr_FR')
{
window.location.replace("index_fr.html");
}
else
{
window.location.replace("index_other.html");
}
}
</script>
Is this method can be use, or do I have to consider other option to deal with my multilanguage app ?
Thanks in advance for any help.

You need to use the callback of getPreferredLanguage:
var handleDeviceReady = function (event)
{
navigator.globalization.getPreferredLanguage(
function (language)
{
console.log("language: " + language.value + '\n');
redirectToLocaleSpecificLogin(language.value);
},
function ()
{
console.log("Error getting language\n");
redirectToLocaleSpecificLogin("en");
}
);
};
document.addEventListener("deviceready", handleDeviceReady, false);
Then inside of your callback (redirectToLocaleSpecificLogin in this case), you can do your redirects.

most of the browsers use language property, IE uses userLanguage
var lang = window.navigator.userLanguage || window.navigator.language;
this should work in IE, SAFARI, CHROME and FF
Edit:
JavaScript for detecting browser language preference this link has more detailed discussion on this topic

Related

Make fullscreen API code work cross browser

On my page I have following code, which I use for making some object a full screen one
<script>
$(document).ready(function(){
$('.fs-button').on('click', function(){
var elem = document.getElementById('fullscreen');
if (document.webkitFullscreenElement) {
document.webkitCancelFullScreen();
} else {
elem.webkitRequestFullScreen();
};
});
});
</script>
Problem is its working only in Chrome. Can you please give me cross browser version of this code? Cannot do this by myself because of poor JS knowledge.
You can use this.
Reference : https://msdn.microsoft.com/en-us/library/dn265028(v=vs.85).aspx
// Initiated by a user click on an element
function makeFullScreen(divObj) {
//Use the specification method before using prefixed versions
if (divObj.requestFullscreen) {
divObj.requestFullscreen();
}
else if (divObj.msRequestFullscreen) {
divObj.msRequestFullscreen();
}
else if (divObj.mozRequestFullScreen) {
divObj.mozRequestFullScreen();
}
else if (divObj.webkitRequestFullscreen) {
divObj.webkitRequestFullscreen();
} else {
console.log("Fullscreen API is not supported");
}
}
once after writing that function, you just need to call inside click event handler as..
$(document).ready(function(){
$('.fs-button').on('click', function(){
var elem = document.getElementById('fullscreen');
//call that function to make it fullscreen.
makeFullScreen( elem );
});
});

Javascript function create element conditional

I am not a programmer, however I have been trying to look at similar samples to come up with my own version, here is what I am trying to do.
<script type="text/javascript">
var advertContainer = null;
var adblocked = null;
function Checkads() {
if ($('.wp_bannerize').height() == 0) {
var adblocked = document.createElement("span");
var adnotice = document.createTextNode("Please support our website by enabling ads");
adblocked.appendChild(adnotice);
var advertContainer = document.getElementById("wp_bannerize");
advertContainer.appendChild(adblocked);
};
}
$(document).ready(function(){
Checkads();
});
</script>
However I am getting an error : Uncaught Type error: Cannot call method append child "null"
Can anyone help me fix it
Update
Here is the much nicer and better code, however the text can only be visible in the source code and not on the website.
<script type="text/javascript">
function checkads() {
if ($('.wp_bannerize').height() == 0) {
$('<div id="adnotice">').text('Please support our website by enabling ads').appendTo('.wp_bannerize');
};
}
$(document).ready(function(){
checkads();
});
</script>
You use a class selector with jQuery:
$('.wp_bannerize')
But an ID selector with the native DOM method:
document.getElementById("wp_bannerize");
They're not the same. To fix your script, replace getElementById('wp_bannerize') with getElementsByClassName('wp_bannerize')[0], or just do it with jQuery:
if ($('.wp_bannerize').height() == 0) {
$('<span>').text('Please support our website by enabling ads').appendTo('.wp_bannerize');
}

Start speech recognizer on Android using Phonegap

Currently I'm making a Phonegap application.
I want to combine augmented reality en speech input.
There is a plugin for Phonegap called SpeechRecognizer, But I can't get it to work.
My header:
<script type="text/javascript" src="cordova-2.6.0.js"></script>
<script type="text/javascript" src="SpeechRecognizer.js"></script>
<script type="text/javascript" charset="utf-8">
document.addEventListener("deviceready", onDeviceReady, false);
function speechOk() {
alert('speech works');
}
function speechFail() {
alert("speech doesn't work");
}
function onDeviceReady() {
window.plugins.speechrecognizer.init(speechOk, speechFail);
}
$("#micButton").bind("touchstart", function() {
var requestCode = 4815162342;
var maxMatches = 1;
var promptString = "What do you want?";
window.plugins.speechrecognizer.startRecognize(speechOk, speechFail, requestCode, maxMatches, promptString);
});
</script>
A picture of the project (config.xml):
Thanks in advance
Is not your fault, the SpeechRecognizer.java has a bug inside.
I had the same problem and I solved it with just replacing the Speech Recognizer plugin with and older version (like 2.0.0), you can download it from github.
It worked for me with Phonegap 2.5.0, guess it works in 2.6.0.
There were a few problems.
First of all, the SDK version wasn't right. If you use the new cordova you also have to use the newest version of the plugin. This version requires SDK 15 or higher. (android manifest -> <uses-sdk android:minSdkVersion="15" android:targetSdkVersion="17" />).
After that, for some reason the plugin init does not return anything.
I just triggerd the: window.plugins.speechrecognizer.startRecognize(); function on a button click, and it executes.
The javascript (you need jQuery for this code):
$("#micButton").bind("touchstart", function() {
var requestCode = 4815162342;
var maxMatches = 1;
var promptString = "What do you want?";
window.plugins.speechrecognizer.startRecognize(speechOk, speechFail, requestCode, maxMatches, promptString);
});
function speechOk(result) {
var match, respObj;
if (result) {
respObj = JSON.parse(result);
if (respObj) {
var response = respObj.speechMatches.speechMatch[0];
$("#searchField").val(response);
$("#searchButton").trigger("touchstart");
}
}
}
function speechFail(m) {
navigator.notification.alert("Sorry, I couldn't recognize you.", function() {}, "Speech Fail");
}
'#micButton' is the button you have to press to start the android voice recognition
'#searchField' is a input field wich gets the result from the voice recognition
Thanks to MrBillau for the good advice.

conditionally loading external javascript libraries in my plugin

I have written a plugin that depends on external libraries that I want to include conditionally, that is, the user can choose to not have them be included automatically in case the user's web site already has those libraries. Here is some pseudocode to illustrate the issue
<script type="text/javascript" src="path/to/plugin.js"></script>
<script type="text/javascript">
PLUGIN.init({
"param1": "foo",
"parma2": 33,
"include": {"jquery": 0, "googlemaps": 0}
});
</script>
In my plugin script
var PLUGIN = {
"init": function(obj) {
if (obj.include.googlemaps !== 0) {
document.write('<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=true&v=3.6">\x3C/script>');
}
if (obj.include.jquery !== 0) {
document.write('<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.js">\x3C/script>');
}
.. do more things ..
}
The problem is that when I am ready to "do more things," the libraries don't seem to be loaded yet. I get an error that jquery not found, or google maps not found. I can solve this by changing my code to
document.write('<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=true&v=3.6">\x3C/script>');
document.write('<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.js">\x3C/script>');
var PLUGIN = {
"init": function(obj) {
.. do more things ..
}
but now the user can't control loading the libraries or not loading them. Suggestions? Workarounds?
Update: Thanks for the suggestions, you all, but no joy so far. Here is what I am doing, and what is happening. Since I am potentially loading 0 or more scripts (the user can optionally decide which scripts need not be loaded), I have made my code like so
"importLib": function(libPath, callback) {
var newLib = document.createElement("script");
if (callback !== null) {
newLib.onload = callback;
}
newLib.src = libPath;
document.head.appendChild(newLib);
},
"init": function(obj) {
var scripts = [];
if (obj.include.googlemaps !== 0) {
scripts.push("http://maps.google.com/maps/api/js?sensor=true&v=3.6");
}
if (obj.include.jquery !== 0) {
scripts.push("http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.js");
}
if (obj.include.anotherlib !== 0) {
scripts.push("http://path/to/another/lib.js");
}
var len_scripts = scripts.length,
callback = null;
if (len_scripts > 0) {
for (var i = 0; i < len_scripts; i++) {
// add callback only on the last lib to be loaded
if (i == len_scripts - 1) {
callback = function() { startApp(obj) };
}
importLib(scripts[i], callback);
}
}
// Start the app rightaway if no scripts need to be loaded
else {
startApp(obj);
}
},
"startApp": function(obj) {
}
What happens is that Firefox croaks with a attempt to run compile-and-go script on a cleared scope error, and Safari doesn't get that error, but doesn't load anything. Funnily, Safari error console shows no error at all. Seems like the Firefox error is caused by the line document.head.appendChild(newLib); which, if I comment, the error goes away, but of course, the web page doesn't load correctly.
You should add each script as a DOM node and use the onload attribute to take action when it has completed loading.
function importLib(libPath, callback) {
var newLib = document.createElement("script");
newLib.onload = callback;
newLib.src = libPath;
document.head.appendChild(newLib);
}
Above, the libPath argument is the URL of the library, and the callback argument is a function to call when loading is complete. You could use it as follows:
importLib("http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.js", function() {
alert("jquery loaded!");
nowDoSomething(aboutIt);
});
By the way: in general, document.write is not a good solution for most problems (but I won't say never the right solution -- there are exceptions to every rule).
the above solution would work in modern browsers but for IE 7/8 u might wanna added little extra code, something like this:
function importLib(libPath, callback) {
var newLib = document.createElement("script");
if (navigator.userAgent.indexOf('MSIE') !== -1) {
newLib.onreadystatechange = function () {// this piece is for IE 7 and 8
if (this.readyState == 'complete') {
callback();
}
};
} else {
newLib.onload = callback;
}
newLib.src = libPath;
document.head.appendChild(newLib);
}
I encountered the same issue. One workaround if you are writing your site in .NET is by conditionally writing the script reference before the page loads from the code behind. My issue is when remote users access my app over VPN, it blocks access to the internet, thus google maps cannot be referenced. This prevents the rest of the page from loading within a reasonable timeframe. I tried controlling the script reference of the google maps library via jQuery's getScript() command, but as you found out, the subsequent google maps configuration code runs before the external library is referenced.
My solution was to conditionally reference google maps from code behind instead:
VB (code behind):
'if VPN mode is not enable, add the external google maps script reference (this speeds up the interface when using VPN significantly)
If Session("VPNMode") = False Then
Dim sb As System.Text.StringBuilder = New System.Text.StringBuilder()
sb.AppendLine("")
sb.AppendLine("<script type='text/javascript'")
sb.Append(" src='http://maps.google.com/maps/api/js?v=3&sensor=false'>")
sb.Append("</script>")
Dim header As LiteralControl = New LiteralControl
header.Text = sb.ToString()
Me.Page.Header.Controls.Add(header)
End If
Client side script (javascript):
<script type='text/javascript'>
$(function () {
if ($("input[name*='VPN']").is(":checked"))
{ }
else {
loadGoogleMap()
}
});
function loadGoogleMap() {
hazsite = new google.maps.LatLng(hazLat, hazLong);
map = new google.maps.Map(document.getElementById('map_canvas'), { zoom: 18, center: hazsite, mapTypeId: google.maps.MapTypeId.SATELLITE });
var marker = new google.maps.Marker({
position: hazsite,
map: map,
title: "Site Location"
});
}
</script>

I can't get ExternalInterface.addCallback to work - trying to call an AS3 function from a js button click

I'm trying to use ExternalInterface.addCallback to allow js to call an as3 method. My code is as follows:
AS:
ExternalInterface.addCallback("sendToActionscript", callFromJavaScript);
function callFromJavaScript():void{
circle_mc.gotoAndStop("finish");
}
JS:
<button type="button" onclick="callToActionscript()">Switch to square</button>
<script type="text/javascript">
function callToActionscript() {
flashController = document.getElementById("jstoactest")
flashController.sendToActionscript();
}
</script>
It's not working. What am I doing wrong?
I set a isFlashReady flag in JS as FALSE. Then when your SWF is loaded, after Event.ADDED_TO_STAGE is fired, I add ExternalInterface.addCallback and flip isFlashReady flag to TRUE. This prevents a call to SWF before it's ready. You might want to throw alert() in JS functions below to see where it's stuck. Hope this helps.
JS:
var isFlashReady = false;
function thisMovie(movieName)
{
if (navigator.appName.indexOf("Microsoft") != -1)
return window[movieName];
}else{
return document[movieName];
}
function callToActionScript(value)
{
if(isFlashReady)
{
thisMovie("SWFID").sendToActionScript();
}
}
function flashReady(value)
{
isFlashReady = true;
}
AS:
if (ExternalInterface.available) {
try {
ExternalInterface.addCallback("sendToActionScript", callFromJavaScript);
flash.external.ExternalInterface.call(flashReady,true);
} catch (error:SecurityError) {
trace("A SecurityError occurred: " + error.message + "\n");
} catch (error:Error) {
trace("An Error occurred: " + error.message + "\n");
}
} else {
trace("External interface is not available for this container.");
}
make sure that AllowScriptAccess is set to "always" or "sameDomain" in embedding the flash and see if that helps. livedocs
Is your SWF file being served from the same Domain as your HTML page? If the domains differ then you will need to use Security.allowDomain to allow the two to communicate.
Also, I've found the easiest way to debug Flash -> JavaScript communication is to use FireBug for Firefox. (sorry I can only post one link!)

Categories