I tried putting the following code into a html and ran it and I uploaded it in my server and opened the link in my Safari browser in my iPhone and the clicked on Show Confirm and no window popups up! Can someone please help.
<!DOCTYPE html>
<html>
<head>
<title>Notification Example</title>
<script type="text/javascript" charset="utf-8" src="http://mobile-web-development-with-phonegap.eclipselabs.org.codespot.com/svn-history/r99/trunk/com.mds.apg/resources/phonegap/js/phonegap-1.0.0.js"></script>
<script type="text/javascript" charset="utf-8">
// Wait for PhoneGap to load
document.addEventListener("deviceready", onDeviceReady, false);
// PhoneGap is ready
function onDeviceReady() {
// Empty
}
// process the confirmation dialog result
function onConfirm(button) {
alert('You selected button ' + button);
}
// Show a custom confirmation dialog
function showConfirm() {
navigator.notification.confirm(
'You are the winner!', // message
onConfirm, // callback to invoke with index of button pressed
'Game Over', // title
'Restart,Exit' // buttonLabels
);
}
</script>
</head>
<body>
<p>Show Confirm</p>
</body>
</html>
The code that you are using (navigator.notification.confirm) is specifically for the mobile platform that is it is meant to run within the PhoneGap mobile application. If you would like to test out the dialogs/confirm messages on a browser before compiling it into an application, I would suggest using a hybrid approach that detects the environment of the application and uses either the native confirm(message) or the PhoneGap specific Notification API. Below is an example Object that has been working for me:
/**
* The object encapsulates messaging functionality to work both in PhoneGap and
* browser environment.
* #author Zorayr Khalapyan
*
*/
var MessageDialogController = (function () {
var that = {};
/**
* Invokes the method 'fun' if it is a valid function. In case the function
* method is null, or undefined then the error will be silently ignored.
*
* #param fun the name of the function to be invoked.
* #param args the arguments to pass to the callback function.
*/
var invoke = function( fun, args ) {
if( fun && typeof fun === 'function' ) {
fun( args );
}
};
that.showMessage = function( message, callback, title, buttonName ) {
title = title || "DEFAULT_TITLE";
buttonName = buttonName || 'OK';
if( navigator.notification && navigator.notification.alert ) {
navigator.notification.alert(
message, // message
callback, // callback
title, // title
buttonName // buttonName
);
} else {
alert( message );
invoke( callback );
}
};
that.showConfirm = function( message, callback, buttonLabels, title ) {
//Set default values if not specified by the user.
buttonLabels = buttonLabels || 'OK,Cancel';
var buttonList = buttonLabels.split(',');
title = title || "DEFAULT TITLE";
//Use Cordova version of the confirm box if possible.
if (navigator.notification && navigator.notification.confirm) {
var _callback = function (index) {
if ( callback ) {
//The ordering of the buttons are different on iOS vs. Android.
if(navigator.userAgent.match(/(iPhone|iPod|iPad)/)) {
index = buttonList.length - index;
}
callback( index == 1 );
}
};
navigator.notification.confirm(
message, // message
_callback, // callback
title, // title
buttonLabels // buttonName
);
//Default to the usual JS confirm method.
} else {
invoke( callback, confirm( message ) );
}
};
return that;
})();
Hope this helps! Let me know if you have any questions.
Related
I want to track the conversion for links in adwords; For this i have the classic code that looks like this(don't worry about values for conversion_id and conversion_label):
<!-- Google Code for Joc Sloturi2 Conversion Page
In your html page, add the snippet and call
goog_report_conversion when someone clicks on the
chosen link or button. -->
<script type="text/javascript">
/* <![CDATA[ */
goog_snippet_vars = function() {
var w = window;
w.google_conversion_id = xxxxxxx;
w.google_conversion_label = "dsadsadsadsadadsa";
w.google_conversion_value = dsadasda;
w.google_conversion_currency = "RON";
w.google_remarketing_only = false;
}
// DO NOT CHANGE THE CODE BELOW.
goog_report_conversion = function(url) {
goog_snippet_vars();
window.google_conversion_format = "3";
var opt = new Object();
opt.onload_callback = function() {
if (typeof(url) != 'undefined') {
window.location = url;
window.open(url, '_blank')
}
}
var conv_handler = window['google_trackConversion'];
if (typeof(conv_handler) == 'function') {
conv_handler(opt);
}
}
/* ]]> */
</script>
<script type="text/javascript"
src="//www.googleadservices.com/pagead/conversion_async.js">
</script>
After that the outbound links are looking like this
Link text whatever
My problem with this is that when I click on the link it opens the link in a new tab and also in the same tab (basically it opens the link twice); Is there a way to only open the link in a new tab in the browser and also track the conversion for it?
I know this is a bit old, but I found a solution. Remove
window.location = url;
Here is my code at the minute:
Using phonegap 2.9
<head>
</head>
<body>
<script charset="utf-8" src="js/cordova.js"></script>
<script>
document.addEventListener("deviceready", onDeviceReady, false);
document.addEventListener("online", onOnline, false);
document.addEventListener("offline", onOffline, false);
// PhoneGap is loaded and it is now safe to make calls PhoneGap methods
//
function onDeviceReady() {
console.log("Device Ready");
}
// Handle the online event
//
function onOnline() {
document.location = 'http://app.dadad.com';
}
function onOffline() {
console.log("Offline");
}
</script>
</body>
However right now I just get a white screen whether i'm connected or not. Eventually what I would like is to display some html when the user is not connected.
So in conclusion:
Would like to fix the function as it is not working
Would like to show html when not connected.
The Online/Offline events do not fire onload. They are there for when you are in app (complete load) and then lose or gain connection. I have gotten around this by doing an initial connection check on load, like this:
function checkConnetcion() {
var networkState = navigator.connection.type;
var states = {};
states[Connection.UNKNOWN] = false;
states[Connection.ETHERNET] = true;
states[Connection.WIFI] = true;
states[Connection.CELL_2G] = true;
states[Connection.CELL_3G] = true;
states[Connection.CELL_4G] = true;
states[Connection.CELL] = true;
states[Connection.NONE] = false;
var connectionStatus = states[networkState];
if(connectionStatus) {
//Do something if connected
}
else{
//Do something if not connected
}
}
Then add this your onready function:
// PhoneGap is loaded and it is now safe to make calls PhoneGap methods
//
function onDeviceReady() {
console.log("Device Ready");
checkConnetcion();
}
You can make use of Jquery ajax and send a dummy request before sending actual request. If you get and Error Code as '0' it means there is no internet connectivity.
$.ajax({
url: 'TestUrl',
type: 'GET',
success: function (data) {
// Go ahead with you request
},
error: function (x, y, z) {
if (x.status == 0) {
alert("Please connect to the internet");
}
else{
alert("Other Error Occured")
}
}
});
Secondly you can also make you of HTML 5 navigator
var condition = navigator.onLine ? "ONLINE" : "OFFLINE";
But it will show ONLINE when WIFI doesn't provide Internet connection.
Cordova connection object will also show WIFI if there is no internet connection
Could some genius help on this issue to sort it out!!! It will be much appreciated
Actually I have flash music player loaded by means of config file named config.xml
Flash player Action script example
**myUltimateMp3Player.loadConfig("config.xml");**
import flash.external.ExternalInterface;
stop();
// ExternalInterface receive
if (ExternalInterface.available) {
ExternalInterface.addCallback("sendTextFromHtml", null, function(val:String):Void {
myUltimateMp3Player.loadConfig(val); });
}
I'm tried to embed the flash dynamically using Swf object,so when a click event handled from a list from html, the corresponding config.xml should be loaded on the flash player.
Sample HTML code:
$( document ).on( "click", "#Musiclist li", function() {
var c = "youtube-playlist";
$("#media-" + c).remove();
createMedia(c);
var id=this.id;
var idxml=id+".xml";
var swfPanel="media-" + c;
var flashvars = {};
var params = {};
params.swliveconnect = "true";
params.allowfullscreen = "true";
params.allowscriptaccess = "always";
var attributes = {};
attributes.id = "flashobj";
attributes.name = "flashobj";
swfobject.embedSWF("source.swf", "flashcontent", "100%", "100%", "9.0.0", "swf/expressInstall.swf", flashvars, params, attributes,callbackFn);
});
callback function
//This function is invoked by SWFObject once the <object> has been created
var callbackFn = function (e){
//Only execute if SWFObject embed was successful
if(!e.success || !e.ref){ return false; }
swfLoadEvent(function(){
var obj=e.ref;
obj.sendTextFromHtml("config.xml");
alert("The SWF has finished loading!");
});
};
Function to hold timer for SWF's PercentLoaded value and waits until it hits "100"
function swfLoadEvent(fn){
//Ensure fn is a valid function
if(typeof fn !== "function"){ return false; }
//This timeout ensures we don't try to access PercentLoaded too soon
var initialTimeout = setTimeout(function (){
//Ensure Flash Player's PercentLoaded method is available and returns a value
if(typeof e.ref.PercentLoaded !== "undefined" && e.ref.PercentLoaded()){
//Set up a timer to periodically check value of PercentLoaded
var loadCheckInterval = setInterval(function (){
//Once value == 100 (fully loaded) we can do whatever we want
if(e.ref.PercentLoaded() === 100){
//Execute function
fn();
//Clear timer
clearInterval(loadCheckInterval);
}
}, 1500);
}
}, 200);}
So I cant figure it out what I'm doing wrong,
The error getting was,
Uncaught ReferenceError: e is not defined
If I'm not using the swfLoadEvent Timer,
The error getting was,
Uncaught TypeError: Object # has no method 'sendTextFromHtml'
e is not a global variable. try modifying your swfLoadEvent function to pass a reference to the swf as an argument:
function swfLoadEvent(swf, fn){
swf.sendTextFromHtml("config.xml");
...
}
which then gets invoked as
swfLoadEvent(e.ref, function(){
...
});
I am building a firefox addon that loads javascript at every page load. I'm using progress listener function I found on this page: https://developer.mozilla.org/en/Code_snippets/Progress_Listeners
My problem is that the code seems to execute to early before the page is fully loaded which causes my script to not run. Here is my code.
var PageLoad = {
browser: null,
domain: null,
oldURL: null,
init: function() {
gBrowser.addProgressListener(urlBarListener,Components.interfaces.nsIWebProgress.NOTIFY_LOCATION);
},
uninit: function() {
gBrowser.removeProgressListener(urlBarListener);
},
processNewURL: function(aURI) {
//if (aURI.spec == this.oldURL)
//return;
MyObject.function();
this.oldURL = aURI.spec;
}
};
var urlBarListener = {
locChange: false,
QueryInterface: function(aIID) {
if (aIID.equals(Components.interfaces.nsIWebProgressListener) ||
aIID.equals(Components.interfaces.nsISupportsWeakReference) ||
aIID.equals(Components.interfaces.nsISupports))
return this;
throw Components.results.NS_NOINTERFACE;
},
onLocationChange: function(aProgress, aRequest, aURI) {
PageLoad.processNewURL(aURI);
},
onStateChange: function(aWebProgress, aRequest, aFlag, aStatus) {},
onProgressChange: function(a, b, c, d, e, f) {},
onStatusChange: function(a, b, c, d) {},
onSecurityChange: function(a, b, c) {}
};
window.addEventListener("load",
function() {
PageLoad.init()
}, false);
var MyObject = {
function : function() {
var script = PageLoad.browser.createElement('script');
script.src = 'url_to_script.js';
PageLoad.browser.getElementsByTagName('head')[0].appendChild(script);
}
};
With this code I get this error message on the console:
PageLoad.browser.getElementByTagName("head")[0] is undefined
If I add a timeout then the script does work intermittently but if the page loads slow I get the same error, here's what works sometimes setTimeout(MyObject.function, 1000);
I need a more reliable way of making sure it's executing the script after the page is loaded.
Unrelated, and it doesn't seem to cause any problems but I also see this error message:
gBrowser.addProgressListener was called with a second argument, which is not supported. See bug 608628.
If you want to load javascript at every page load - the best way is subscribing to DOMContentLoaded event:
var MyObject = {
processDOMContentLoaded: function(doc) {
var script = doc.createElement('script');
script.src = 'url_to_script.js';
script.type = 'text/javascript';
doc.getElementsByTagName('head')[0].appendChild(script);
}
};
window.addEventListener('load', function() {
var appcontent = document.getElementById('appcontent');
if(appcontent != null) {
appcontent.addEventListener('DOMContentLoaded', function(event) {
var doc = event.originalTarget;
if(doc instanceof HTMLDocument) {
MyObject.processDOMContentLoaded(doc);
}
}, true);
}
}, false);
Have not tested, but should work.
You are using onLocationChange method - but if you look at how the browser behaves, the location in the address bar changes as soon as a connection with the server is established. You should look at state changes instead:
onStateChange: function(aWebProgress, aRequest, aFlag, aStatus)
{
if ((aFlag & Components.interfaces.nsIWebProgressListener.STATE_STOP) &&
(aFlag & Components.interfaces.nsIWebProgressListener.STATE_IS_WINDOW))
{
// A window finished loading
PageLoad.windowLoaded(aWebProgress.DOMWindow);
}
},
Note that the window that finished loading is explicitly passed to PageLoad.windowLoaded() - you will be receiving notifications from different tabs and you cannot assume that the notification comes from the foreground tab.
As to the warning you are getting, just leave out the second parameter in the call to gBrowser.addProgressListener():
gBrowser.addProgressListener(urlBarListener);
tabbrowser.addProgressListener() only accepts one parameter, unlike nsIWebProgress.addProgressListener() which has a second parameter.
Actually its a great question.
You should use event listener, but carefully, because if you trigger for every page load its can trigger you more than one time (in the worst case about dozens of times).
So how you can do that?
window.addEventListener("load", function load(event){
window.removeEventListener("load", load, false); //remove listener, no longer needed
myExtension.init();
},false);
var myExtension = {
init: function() {
var appcontent = document.getElementById("appcontent"); // browser
if(appcontent){
appcontent.addEventListener("DOMContentLoaded", myExtension.onPageLoad, true);
}
},
onPageLoad: function(aEvent) {
var doc = aEvent.originalTarget; // doc is document that triggered the event
var win = doc.defaultView; // win is the window for the doc
if (doc.nodeName != "#document") return;
if (win != win.top) return;
if (win.frameElement) return;
alert("the main page has been loaded");
},
};
get notice that we check for the type of the trigger every pageload triggering to prevent multi load.
The answers that were provided were acceptable but I found yet another solution that works perfectly.
var PageLoad = {
init: function() {
if(gBrowser) gBrowser.addEventListener("DOMContentLoaded", this.onPageLoad, false);
},
onPageLoad: function(aEvent) {
var doc = aEvent.originalTarget; // doc is document that triggered the event
var win = doc.defaultView; // win is the window for the doc
if (doc.nodeName != "#document") return;
if (win != win.top) return;
if (win.frameElement) return;
MyAddon.function();
}
}
window.addEventListener("load", function load(event){
window.removeEventListener("load", load, false); //remove listener, no longer needed
PageLoad.init();
},false);
I have an issue in iOS with a HTML5 Offline app. My app works fine offline in Firefox, Chrome and Android 2.2, but not on my iPod Touch running iOS 4.2.1.
Here is my manifest (a JSP), called "1.cache.manifest.jsp". I use a "no-cache.jsp" JSP to ask that the manifest is not cached. I also add "index.jsp" to the manifest, though this is strictly not necessary as it is the resource that references the manifest.
<%#page contentType="text/cache-manifest; charset=UTF-8" pageEncoding="UTF-8"
%><jsp:include page="no-cache.jsp" flush="true"
/><%
String cacheManifestVersion = "20110220 1224";
//System.out.println("Cache manifest version=" + cacheManifestVersion);
%>CACHE MANIFEST
index.jsp
cache-this.js.jsp
Here is my index.jsp page. It listens to the applicationCache events and dumps out the event type. I use a "no-cache.jsp" JSP to ask that the HTML is not cached.
<%#page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"
%><jsp:include page="no-cache.jsp" flush="true"
/><!DOCTYPE html>
<html manifest="1.cache.manifest.jsp">
<head>
<script>
var appCacheEvents = ["checking", "error", "noupdate", "downloading", "progress", "updateready", "cached", "obsolete"];
for (var i = 0; i < appCacheEvents.length; i++) {
applicationCache.addEventListener(appCacheEvents[i], function (evt) {
var el = document.getElementById("applicationCache-events");
el.innerHTML += "applicationCache " + evt.type + " event.<br/>";
}, false);
}
</script>
<script src="./cache-this.js.jsp"></script>
</head>
<body>
<div id="applicationCache-events"></div>
<div id="cache-this-output"></div>
</body>
</html>
The "cache-this.js.jsp" is some javascript that adds some text to the page when loaded:
<%#page contentType="application/javascript; charset=UTF-8" pageEncoding="UTF-8"
%><jsp:include page="no-cache.jsp" flush="true"
/>// cache this
window.addEventListener("load", function (evt) {
var msg = "Script loaded " + new Date();
document.getElementById("cache-this-output").innerHTML = msg;
}, false);
This is the output on those user agents that work, the FIRST time the site is accessed:
applicationCache checking event.
applicationCache downloading event.
applicationCache progress event.
applicationCache progress event.
applicationCache cached event.
Script loaded Sun Feb 20 2011 13:22:33 GMT+0000 (GMT Standard Time)
Subsequently the output is:
applicationCache checking event.
applicationCache noupdate event.
Script loaded Sun Feb 20 2011 13:23:47 GMT+0000 (GMT Standard Time)
And when offline (in Firefox) I get the following. Note the "error" event, but the app DOES work offline (even after I clear the HTTP cache).
applicationCache checking event.
applicationCache error event.
Script loaded Sun Feb 20 2011 13:26:54 GMT+0000 (GMT Standard Time)
On my iPod Touch I get the same output (as first access) EXCEPT the "cached" event is replaced by an "error" event.
Any ideas why iOS is failing to cache the app initially?
Can you see what your status is returning when you're getting your errors? Here's a similar functionality I use, that returns a few additional variables that might help you troubleshoot on your end:
var cacheStatusValues = [];
cacheStatusValues[0] = 'uncached';
cacheStatusValues[1] = 'idle';
cacheStatusValues[2] = 'checking';
cacheStatusValues[3] = 'downloading';
cacheStatusValues[4] = 'updateready';
cacheStatusValues[5] = 'obsolete';
var cache = window.applicationCache;
cache.addEventListener('cached', logEvent, false);
cache.addEventListener('checking', logEvent, false);
cache.addEventListener('downloading', logEvent, false);
cache.addEventListener('error', logEvent, false);
cache.addEventListener('noupdate', logEvent, false);
cache.addEventListener('obsolete', logEvent, false);
cache.addEventListener('progress', logEvent, false);
cache.addEventListener('updateready', logEvent, false);
function logEvent(e) {
var online, status, type, message;
online = (navigator.onLine) ? 'yes' : 'no';
status = cacheStatusValues[cache.status];
type = e.type;
message = 'online: ' + online;
message+= ', event: ' + type;
message+= ', status: ' + status;
if (type == 'error' && navigator.onLine) {
message+= ' (prolly a syntax error in manifest)';
}
console.log(message);
}
window.applicationCache.addEventListener(
'updateready',
function(){
window.applicationCache.swapCache();
console.log('swap cache has been called');
},
false
);
I use this to see the error results on the Ipad, iPhone ot iPod Touch
var bubbleTimeout;
var verboseMessage = true;
function initCache() {
if ( webappCache != null ) {
// create event listeners for all associated events
webappCache.addEventListener('cached', showSave, false);
webappCache.addEventListener('downloading', showWaiting, false);
webappCache.addEventListener('error', errorHandler, false);
webappCache.addEventListener('updateready', updateReady, false);
webappCache.addEventListener('noupdate', updateReady, false);
webappCache.addEventListener('progress', showWaiting, false);
webappCache.addEventListener('checking', showWaiting, false);
}
}
function errorHandler(e) {
if ( verboseMessage ) {
newBubble("phase :"+e.eventPhase+" \n"+
"currentTarget: "+e.currentTarget+"\n"+
"target: "+e.target+"\n"+
"type: "+e.type+"\n"+
"cancelable: "+e.cancelable+"\n"+
"bubbles: "+e.bubbles+"\n"+
"cancelBubble: "+e.cancelBubble+"\n"+
"message: "+e.message+"\n"
);
} else {
// newBubble("Connection Error, prolly bad manifest", false);
}
}
function newBubble( textMsg, showButton ) {
if ( bubbleTimeout ) {
clearTimeout(bubbleTimeout);
}
if ( showButton ) textMsg += "<br /><button type='button' onclick='hideBubble()'>OK</button>";
if ( !document.getElementById("bubble") ) {
var divTag = document.createElement("div");
divTag.id = "bubble";
divTag.className ="bubble";
document.getElementById("theFrame").appendChild(divTag);
divTag.innerHTML = textMsg;
divTag.style.visibility = "visible";
} else {
document.getElementById("bubble").innerHTML = textMsg;
document.getElementById("bubble").style.visibility = "visible";
}
bubbleTimeout = setTimeout("hideBubble()",15000);
}
function hideBubble() {
$('#bubble').css('visibility','hidden');
}