Cordova inappbrowser: executeScript on loadstart - javascript

Is it possible to executeScript() on loadstart event in Cordova inAppBrowser? Here is my standalone example I made to try to make it happen:
<!DOCTYPE html>
<html>
<head>
<title>Standalone Example</title>
<script type="text/javascript" charset="utf-8" src="cordova.js"></script>
<script type="text/javascript" charset="utf-8">
document.addEventListener("deviceready", onDeviceReady, false);
var iabRef = null;
function testFunction() {
iabRef.executeScript({
code: {'alert("It is alive! ALIVE!")'}
});
}
function onDeviceReady() {
iabRef = window.open('http://telegraph.co.uk', '_self', 'location=no', 'zoom=no', 'hardwareback=yes');
iabRef.addEventListener('loadstart', testFunction);
}
</script>
</head>
<body>
</body>
</html>
Doesn't work for me though. Config.xml allow origin is set to *. Any suggestions?
Thanks!

Yes, it possible to executeScript() on loadstart.Remove {} from alert part as follows:
function testFunction() {
iabRef.executeScript({
code: 'alert("It is alive! ALIVE!");'
});
}
Hope this works

After a little bit of wandering I found that changing "_self" to "_blank" makes it work. So:
iabRef = window.open('http://telegraph.co.uk', '_blank', 'location=no', 'zoom=no', 'hardwareback=yes');

Related

cordova android backbutton behavior [duplicate]

I am overriding my device back button per the documentation that I attach event listener to backbutton with argument of false after the deviceready event.
I have done so like this:
// Smart App object
define([
'routes',
'cordova',
'angular',
'angularRoute',
'angularResource',
'angularTouch',
'config',
'controllers',
'services',
'directives',
'helpers'
], function(appRoute) {
var oApp = {
_app: {},
init: function() {
console.log('init');
document.addEventListener('deviceready', this.onDeviceReady, false);
},
onDeviceReady: function() {
console.log('ok device ready');
document.addEventListener('backbutton', function() {
console.error('deviceback start');
angular.element('.ng-scope').scope().back();
console.error('deviceback end');
}, false);
// ...
}
// ...
I have worked crazily to figure out why hitting the device button is not triggering this backbutton event i attached, i dont even see the console.error messages in the console. I am testing on Android right now I haven't tested on any of the other Phone OS'es yet.
The console.log('ok device ready') does fire and my app works properly, the device backbutton is overridden in that its default functionality is not taking place, however as stated, my function is not taking place either.
I read other stackoverflow topcis and they said the Cordova version landed a fix, but my Cordova version is much after theirs, my .cordova/config.json file tells me:
{
"lib": {
"www": {
"id": "com.tigoenergy.smart",
"version": "3.5.0"
}
}
}
It is 3.5 and then my info.txt tells me it is 5.0.0:
Node version: v0.10.25
Cordova version: 5.0.0
Config.xml file:
<?xml version="1.0" encoding="UTF-8"?>
<!-- config.xml reference: https://build.phonegap.com/docs/config-xml -->
<widget xmlns = "http://www.w3.org/ns/widgets"
xmlns:gap = "http://phonegap.com/ns/1.0"
Does anyone have any ideas?
Try using the normal way of using cordova events.
// device APIs are available
//
function onDeviceReady() {
// Register the event listener
document.addEventListener("backbutton", onBackKeyDown, false);
}
// Handle the back button
//
function onBackKeyDown() {
//Add your back button implementation.
}
official documentation here
Modified code
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/html">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no" />
<meta name="apple-mobile-web-app-capable" content="yes" />
<title>Tigo SMART Installation</title>
<script type="text/javascript" src="apps/installation/js/jquery-2.1.1.min.js"></script>
<script type="text/javascript" src="cordova.js"></script>
<script type="text/javascript" src="apps/installation/js/index.js"></script>
<script type="text/javascript" src="apps/installation/js/fastclick.min.js"></script>
<script type="text/javascript" src="apps/installation/js/sha512.js"></script>
<script type="text/javascript" src="bower_components/uri.js/src/URI.min.js"></script>
<script type="text/javascript" src="js/extlogin.js"></script>
<link rel="stylesheet" href="css/app.css">
<link rel="stylesheet" type="text/css" href="apps/installation/css/index.css" />
<script type="text/javascript" charset="utf-8">
$(document).ready(function(){
//mycode
console.log('ok loaded');
document.addEventListener("deviceready", onDeviceReady, false);
});
// Wait for device API libraries to load
//
/*function onLoad() {
console.warn('ok loaded')
document.addEventListener("deviceready", onDeviceReady, false);
}
*/
// device APIs are available
//
function onDeviceReady() {
// Register the event listener
console.log('ok device ready');
document.addEventListener("backbutton", onBackKeyDown, false);
}
// Handle the back button
//
function onBackKeyDown() {
console.log('ok backey downed');
}
</script>
</head>
<body>
<div ng-view></div>
<script data-main="bin/SmartApp" src="bower_components/requirejs/require.min.js"></script>
<img style="opacity:0;visibility:hidden;" class="loader" src="img/loader.gif" />
</body>
</html>
Few reference links here and here
The issue was I was importing cordova.js in an iframe even though it was already in the parent window scope. I didn't know it would break it and thought I had to import cordova.js in the iframe. Removing the from the iframe fixed it.
Try This
$(document).ready(function () {
document.addEventListener("backbutton", onBackKeyDown, false);
});
function onBackKeyDown() {
alert('ok backey downed');
}
Make sure these files are link in your page
<script type="text/javascript" src="cordova.js"></script>
<script type="text/javascript" src="scripts/platformOverrides.js"></script>
<script type="text/javascript" src="scripts/index.js"></script>

Firefox incompatibility?

http://ahmedstudio.za.pl/firefoxerror/
It works in chrome, opera but doesn't get along with Firefox.
The whole javascript thing is not applying.
This is directly in my javascript.js:
window.onload = function() {
todo("body", 50);
alert("alert!");
setTimeout(function () {
todo("body", 0);
}, 1000)
}
function todo(element, size) {
//blahblah
}
Even if it doesn't actually solve your problem I'd like to share my findings about replacing event handlers with invalid function calls. I've composed this little fiddle:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JS Bin</title>
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
<script>
jQuery(function(){
$("body").on("load", function(){
$(this).append("Should not run")
});
});
</script>
</head>
<body onload="doesNotExist()">
</body>
</html>
Firefox, Explorer and Edge actually replace the <body> event handler. However, Chrome ignores the onload="doesNotExist()" and execute previous handler.
In the land of tag soup it's hard to decide which workaround is the correct one but it's definitively a bug that could explain your symptoms.
function load() {
//do stuff
}
and the appropriate
<body onload="load()"> </body>
This runs fine in me. I even tried to create a dummy page with this snippet but could not replicate it.Here is snippet.Since the snippet you shared does not contain jquery , i opt to use same code .
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>
<body>
<script>
window.onload = function(){
_todo({
a:'body',
b:50,
alertFrom:'window.onload'
});
setTimeout(function(){
_todo({
a:'body',
b:0,
alertFrom:'setTimeOut'
});
},1000);
};
function _todo(options){
var a = options.a;
var b = options.b;
var c=options.alertFrom
alert(c +" "+a +" "+b);
};
</script>
</body>
</html>
Also note that there is a importance of semicolon after a function.
Here are couple of snapshots

How to call a function that is in a js file from another js file

I know this question has been answered many times but the solutions in those questions aren't working for me. I have a function in lets suppose, a.js. This function is outside the document.ready function and here is its format:
function thisIsFromAnotherFile(){
alert("This alert is from another js file");
}
I'm calling this function from the other file, b.js this way:
var openFile = function(context){
thisIsFromAnotherFile();
}
openFile is an onclick function.
onclick = "openFile(this)"
When I run this code I'm getting an
Uncaught ReferenceError: thisIsFromAnotherFile is not defined. Please help me out. Thanks.
It seems likely there's a few things you're not telling us.
The following code provides a minimal, functioning example.
file1.html
<!DOCTYPE html>
<html>
<head>
<script>
"use strict";
window.addEventListener('load', onDocLoaded, false);
function onDocLoaded()
{
}
</script>
<script src="filea.js"></script>
<script src="fileb.js"></script>
<style>
</style>
</head>
<body>
<button onclick='fromFileA();'>Fire func in filea.js</button>
</body>
</html>
filea.js
function fromFileA()
{
fromFileB();
}
fileb.js
function fromFileB()
{
alert("now in fileb.js");
}
A function cannot be called unless it was defined in the same file or one loaded before the attempt to call it.
You declare function fn1 in File1.js, and then in File2 you can just have fn1();
File1.js
function thisIsFromAnotherFile() {
alert("working");
}
File2.js
function openFile() {
thisIsFromAnotherFile();
}
**HTML**
<html>
<head>
<script src="File1.js" type="text/javascript"></script>
<script src="File2.js" type="text/javascript"></script>
</head>
<body>
<button onclick="openFile()">Click me</button>
</body>
</html>
you need to load a.js before you call the function
<head>
<script type="text/javascript" src="path/to/a.js"></script>
</head>

AngularJS including javascript in HTML

Could someone explain why this is working:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" ng-app="appLogin">
<head>
<script src="../Scripts/jquery-2.1.0.min.js"></script>
<script src="../Scripts/angular.min.js"></script>
<script src="../Global/config.js"></script>
</head>
<body>
</body>
</html>
But when I try to add my config.js script like this:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" ng-app="appLogin">
<head>
<script src="../Scripts/jquery-2.1.0.min.js"></script>
<script src="../Scripts/angular.min.js"></script>
<script>
var element1 = document.createElement("script");
element1.src = "../Global/config.js";
document.head.appendChild(element1);
</script>
</head>
<body>
</body>
</html>
I get:
Uncaught Error: [$injector:modulerr] http://errors.angularjs.org/1.2.13/$injector/modulerr?p0=appLogin&p1=Error%….c%20(http%3A%2F%2Flocalhost%3A49723%2FScripts%2Fangular.min.js%3A17%3A431)
appLogin is my angular module defined in config.js. In both cases when I use developer tools in my browser I see that the script is loaded but for some reason the second approach is not working?
the second example tries to download and create the module asynchronously.
so, there is a chance that 'appLogin' does not yet exist when angular tries to bootstrap.
unlike the first example, browsers wait for the script tag to finish. so, the document's ready event is not yet fired.
i can remember, that auto-bootstrap begins when the ready event is fired.
I got it now.
As all of you mentioned, the problem is that appLogin does not exist yet.
I solved my problem using document.readyState():
<script type="text/javascript">
function getConfig() {
var element1 = document.createElement("script");
element1.src = "../config.js";
document.body.appendChild(element1);
}
if (document.readyState === "complete") { getConfig(); }
</script>
Thank you guys. :)
you can try something like this
<script type="text/javascript">
function getConfig() {
var element = document.createElement("script");
element1.src = "../Global/config.js";
document.body.appendChild(element);
}
if (window.addEventListener)
window.addEventListener("load", getConfig, false);
else if (window.attachEvent)
window.attachEvent("onload", getConfig);
else window.onload = getConfig;
</script>

PhoneGap Cordova 3.1.0 inAppBrowser EventListener not working

I'm starting to use Cordova 3.1.0 now. I use command line to generate a project and then modify the existing code.
I copy and paste the following code from official website to test.
<!DOCTYPE html>
<html>
<head>
<title>InAppBrowser.addEventListener Example</title>
<script type="text/javascript" charset="utf-8" src="cordova.js"></script>
<script type="text/javascript" charset="utf-8">
// Wait for device API libraries to load
//
document.addEventListener("deviceready", onDeviceReady, false);
// device APIs are available
//
function onDeviceReady() {
var ref = window.open('http://apache.org', '_blank', 'location=yes');
ref.addEventListener('loadstart', function(event) { alert('start: ' + event.url); });
ref.addEventListener('loadstop', function(event) { alert('stop: ' + event.url); });
ref.addEventListener('loaderror', function(event) { alert('error: ' + event.message); });
ref.addEventListener('exit', function(event) { alert(event.type); });
}
</script>
</head>
<body>
</body>
</html>
This doesn't work. There are no alert. Then I added a button to try to fire the events.
<!DOCTYPE html>
<html>
<head>
<title>InAppBrowser.addEventListener Example</title>
<script type="text/javascript" charset="utf-8" src="cordova.js"></script>
<script type="text/javascript" charset="utf-8" src="jquery.js"></script>
<script type="text/javascript" charset="utf-8">
// Wait for device API libraries to load
//
document.addEventListener("deviceready", onDeviceReady, false);
// device APIs are available
//
function onDeviceReady() {
$("#btn").click(function(){
var ref = window.open('http://apache.org', '_blank', 'location=yes');
ref.addEventListener('loadstart', function(event) { alert('start: ' + event.url); });
ref.addEventListener('loadstop', function(event) { alert('stop: ' + event.url); });
ref.addEventListener('loaderror', function(event) { alert('error: ' + event.message); });
ref.addEventListener('exit', function(event) { alert(event.type); });
});
}
</script>
</head>
<body>
<button id="btn">trigger</button>
</body>
</html>
This time, it works with second time. It means, it doesn't work when I click the button first time. But it works at the second time when I click the button. After that, I use console log inside the callback function to debug. The logs were not appeared at the first time (appeared at the second time and third, forth....).
I don't really know why this happened. I followed all steps from official website. Creating project, installing plugin, building and so on.
Could someone give me a hand?
I ran into the same problem. On further investigation, I found that the events weren't firing in the emulator / browser, but fired fine on the Nexus 7 device that I do my testing on. Hope that helps!
It looks like it's a problem with the last phonegap/cordova version 3.1.0.
https://groups.google.com/forum/#!topic/phonegap/e5_5unC2fYs
Try an older version.

Categories

Resources