Ti.App.fireEvent - Reference error Ti is not defined - javascript

I have this simple Titanium js script.
app.js
var win = Ti.UI.createWindow();
var webview = Ti.UI.createWebView({
url: 'logging.html'
});
webview.addEventListener('help',function(){
alert('help');
});
win.add(webview);
win.open();
logging.html
<html>
<body>
<a onclick="Ti.App.fireEvent('help')">Help</a>
</body>
</html>
when I click on the Help link, the console gives me Reference Error: Ti is not defined.
I also tried changing Ti with Titanium, but same error.
------------- EDIT ----------
this error comes only with web browser. iOS works perfectly. but
when titanium studio compiles the project for web mobile, I can see titanium.js and TI/* folder, so I guess it can't load Ti object. can anyone explain me why?

I found a solution!
simply add to all of your html pages the simple script below
var Ti = window.parent.Ti
have fun!
EDIT:
from sdk version 3.0.2GA on, I guess they fixed it. now it calls Ti sdk without that hack!**

First, change:
webview.addEventListener('help',function(){
alert('help');
});
To:
Ti.App.addEventListener('help',function(){
alert('help');
});
And second: Call "Ti.App.fireEvent()" without the final "s" in your HTML file.

after some tests, I found that the previous code works perfectly on iOS phisical device/simulator and Android.
it doesn't on android web browser emulator and normal mobile browser (Firefox as mobile web app)
so, it seems that Titanium api calls will never work on web browsers because of "normal javascript library doesn't have Titanium.* or Ti.*".

I used this and it worked
window.parent.TiApp.fireEvent

Related

Android - cordova - A network error has occurred

My Environment
Android Studio 1.0.1
cordova-4.1.0
I'm trying to access my website at http://example.com/index.php from the line super.loadUrl(Config.getStartUrl());
As the application runs on My physical device (Moto g2, Android 5) splash screen to MainActivity extends CordovaActivity works fine but on MainActivity it shows a alert with a title: Application Error and body: There was a network error. (http://example.com/index.php)
I have set the needed permission for Internet Access AndroidManifest.xml
Recently i have updated cordova from 2.9 to 4.1.; Log cat doesn't show's any record related to my application while running application. Also i tried to replace "http://example.com/index.php" with the "file:///android_asset/www/example.html" which worked fine, so i made a change in it and redirected to "http://example.com/index.php" form onLoad or by giving link it from example.html page but it fails to redirect.
anybody has a solution or a trick to solve it?
Add www before example. like this http://www.example.com/index.php it should work.
If still it is not working try debugging using chrome. This link might help you
http://www.html5rocks.com/en/tutorials/developertools/mobile/

Intel xdk function (cookie) works fine in emulator, but doesnt work in device even i have put <script src="intelxdk.js"></script> tag in index.html

I am trying to test cookie in device, so i build a simple application.
I have tested it on emulator and works fine.
but when i test it in apps testing server, and in device, All the Intel xdk function doesnt work (I just want test cookie),
I have put script <script>src="intelxdk.js"</script> in index.html.
But it doesnt work also, i have searched here,
intel-xdk html5 platform android aplication working properly in emulator but not working properly in device , so i include the <script src="xhr.js"></script> but it doesnt work also
My code is:
(Sorry, im just new here and cant post image if post under 10. Here the image)
http://helpmedong.esy.es/
The alert is still : Intel is not defined..
thx before..
ive found the problem.
I click "Project" button =>
then click +plugin tab =>
featured and custome cordova plugins =>
check the cache option.
Thx everyone.
And then put the coding in deviceready.
About my comment above and with cheyong help, I go to this way...
If you begin with project withou Cordova you click second option
But, in this way haven't plugins choice:
Than upgrade...
Note the option "plugins"

Deeplinking mobile browsers to native app - Issues with Chrome when app isn't installed

I have a webpage, lets call it entry.html.
When a user enters this page, a javascript code (see below) is attempting to deep-link the user to the native iOS / Android app.
If the deep-link fails (probably if the app isn't installed on device), user should "fall back" to another page- lets call it fallback.html.
here is the javascript code that is running on entry.html:
$(function(){
window.location = 'myapp://';
setTimeout(function(){
window.location = 'fallback.html';
}, 500);
});
this is a standard deep-linking method that is recommended all over the network; try to deep-link, and if the timeout fires it means that deep-link didn't occur- so fallback.
this works fine, as long app is installed on device.
but if the app isn't installed, this is the behaviour when trying to deep-link:
Mobile Safari: I see an alert message saying "Safari cannot open this page..." for a moment, and then it falls-back properly to fallback.html- which is the expected behaviour.
Mobile Chrome is my problem.
when the app isn't installed, browser is actually redirected to the myapp:// url, which is of course, invalid- so i get a "not found" page, and fall-back doesn't occur.
Finally- my question is:
How can I fix my code so FALL-BACK WILL OCCUR on mobile Chrome as well? just like mobile Safari?
note: i see that LinkedIn mobile website does this properly, with Safari & Chrome, with or without the app installed, but i couldn't trace the code responsible for it :(
note2: i tried appending an iframe instead of window.location = url, this works only on Safari, mobile Chrome doesn't deep-link when appending an iFrame even if app is installed.
Thanks all!
UPDATE:
i found a decent solution, and answered my own question. see accepted answer for my solution.
for whoever is interested, i managed to find a decent solution to solve these issues with deeplinking Chrome on Android.
i abandoned the myapp:// approach, i left it functioning only in cases of an iOS device.
for Android devices, i'm now using intents which are conceptually different than the myapp:// protocol.
I'm mainly a web developer, not an Android developer, so it took me some time to understand the concept, but it's quite simple. i'll try to explain and demonstrate MY solution here (note that there are other approaches that could be implemented with intents, but this one worked for me perfectly).
here is the relevant part in the Android app manifest, registering the intent rules (note the android:scheme="http" - we'll talk about it shortly):
<receiver android:name=".DeepLinkReceiver">
<intent-filter >
<data android:scheme="http" android:host="www.myapp.com" />
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.BROWSABLE"/>
<category android:name="android.intent.category.DEFAULT"/>
</intent-filter>
</receiver>
now, after this is declared in the app manifest, i'm sending myself an email with "http://www.myapp.com" in the message.
when link is tapped with the Android device, a "chooser" dialog comes up, asking with which application i want to open the following? [chrome, myapp]
the reason this dialog came up upon tapping on a "regular" url, is because we registered the intent with the http scheme.
with this approach, the deeplink isn't even handled in the webpage, it's handled by the device itself, when tapping a matching link to an existing intent rule defined in the Android app manifest.
and yes, as i said, this approach is different by concept than the iOS approach, which invokes the deeplink from within the webpage, but it solves the problem, and it does the magic.
Note: when app isn't installed, no chooser dialog will come up, you'll just get navigated to the actual web page with the given address (unless you have more than 1 browser, so you'll need to choose one... but lets not be petty).
i really hope that this could help someone who's facing the same thing.. wish i had such an explanation ;-)
cheers.
It is very important to make sure that when you try to open a deeplink URL with JavaScript that the URL is properly formatted for the device and browser. (If you do not use the appropriate deeplink URL for the browser/platform, a user may be redirected to a “Page Not Found”, which is what you experience.)
Now you must note that Chrome on Android has a different URL format than the old standard Android browser 1! You need to annotate the deep links using href="android-app://" in the HTML markup of your web pages. You can do this in the section for each web page by adding a tag and specifying the deep link as an alternate URI.
For example, the following HTML snippet shows how you might specify the corresponding deep link in a web page that has the URL example://gizmos.
<html>
<head>
<link rel="alternate"
href="android-app://com.example.android/example/gizmos" />
...
</head>
<body> ... </body>
For more details, see the references here:
https://developer.chrome.com/multidevice/android/intents
https://developers.google.com/app-indexing/webmasters/server
https://developer.android.com/training/app-indexing/enabling-app-indexing.html#webpages
And here's a deep link testing tool for Android: https://developers.google.com/app-indexing/webmasters/test.html
Hope that helps.
1 Since the old AOSP browser was replaced by chromium, this is now the default way to handle deep links for recent Android versions. Nonetheless, Android still requires a conditional soltion, because older OS versions still use the AOSP browser.
I have created a Javascript plugin, which supports most of the modern browsers on mobile. But it requires to have deep linking landing pages to be hosted on cross domain(different than universal link url) to work on ios9 Facebook using universal linking. There is also different way to get that working on the Facebook iOS9 using Facebook SDK. I am sharing this if anyone might find this helpful. Currently it does not fallback option, but if falls back to the App Store.
https://github.com/prabeengiri/DeepLinkingToNativeApp
I am Using this Code to for deeplinking.
If the app is installed the app will open up..
If the app is not installed then this remains as it is..
If you wish to add any other condition for app no install then just uncomment the setTimeout code .
<script>
var deeplinking_url = scootsy://vendor/1;
$(document).ready(function(){
call_me_new(deeplinking_url);
});
var call_me_new = function(deeplinking_url){
if(deeplinking_url!=''){
var fallbackUrl ='http://scootsy.com/';
var iframe = document.createElement("iframe");
var nativeSchemaUrl = deeplinking_url;
console.log(nativeSchemaUrl);
iframe.id = "app_call_frame";
iframe.style.border = "none";
iframe.style.width = "1px";
iframe.style.height = "1px";
iframe.onload = function () {
document.location = nativeSchemaUrl;
};
iframe.src = nativeSchemaUrl; //iOS app schema url
window.onload = function(){
document.body.appendChild(iframe);
}
//IF the App is not install then it will remain on the same page.If you wish to send the use to other page then uncomment the below code and send a time interval for the redirect.
/*
setTimeout(function(){
console.log('Iframe Removed...');
document.getElementById("app_call_frame").remove();
window.location = fallbackUrl; //fallback url
},5000);*/
}
};
</script>
setTimeout(function () { if (document.hasFocus()) { window.location = 'URL WILL BEHERE';} }, 2000);
window.location = 'app://';
Need to check document.hasFocus() here because if app is open then playstore url is also open in browser
I also had similar issue, there is a possible alternative for this. If the app is not installed on user's device we can redirect that to some other url.To know more about it Check Here
Example:
Take a QR code
In my case its working fine in opera and chrome browser my deeplink url is
"intent://contentUrl + #Intent;scheme=" +envHost +;package="+envHost+";end";
For other browser create iframe and append the url.
Note -: iframe url append having issue with old device and in firefox its opening app dialog .

Why does Cordova 2.7.0 JS seemingly no longer work on remote pages?

Background
I'm attempting to upgrade an iOS app built on Cordova 2.0 to version 2.7.
It's basically a welcome screen that points to a remote search engine (please withhold comments about app validity and likely approval, as we're past that), and we were using the ChildBrowser plugin to enable opening links in a sub browser so as not to trap the user in the Cordova webview.
Cordova 2.7 has a feature called InAppBrowser I am hoping to use instead of ChildBrowser. InAppBrowser does essentially the same thing, aside from missing a button to open in Safari.
Problem
The existing app's remote webpages include the Cordova JS (as well as that for the ChildBrowser plugin) and it works fine for opening links in the sub browser.
My test Cordova 2.7 app doesn't seem to load the Cordova JS correctly when it's being loaded from a remote web page.
I tried using this exact same HTML on the embedded start page and a remote start page:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script type="text/javascript" src="http://mydomain.com/mobile/cordova-2.7.0.js"></script>
</head>
<body>
<script>
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
alert("Ready!!");
}
</script>
</body>
</html>
To test this as the embedded start page, I put this line in config.xml:
<content src="index.html" />
When I run the app, I promptly get the "Ready!" alert.
To test this as the remote start page (I'm aiming to link to the remote page in the final app, I am just using it as the start page for testing. The result is the same if I link from the embedded page.), I put this line in config.xml:
<content src="http://mydomain.com/mobile/index.php" />
When I run the app, I just get the blank screen and no alert.
Further, in cordova-2.7.0.js L. 6255, I changed
console.log('deviceready has not fired after 5 seconds.');
to
alert('deviceready has not fired after 5 seconds.');
With that change, running the app using the remote start page causes the blank page, and then after five seconds, I get the alert "deviceready has not fired after 5 seconds.". So this tells me Cordova JS is not starting correctly. Needless to say, I can't get InAppBrowser to launch links in the sub browser on the remote site, but I can get it working just fine on the embedded start page.
Anyone have any ideas of where to go from here? This is a pretty simplistic example, so I'm assuming this is a Cordova settings problem or a change in the functionality. I appreciate any thoughts, thanks!
Yes, something broke in 2.7 - related to our cordova-cli work. See: https://issues.apache.org/jira/browse/CB-3029
The fix is to add an empty file called "cordova_plugins.json" in your root folder.
I had a similar problem relating to upgrading to Cordova 2.7. However my problem was all my console.logs stopped firing when running the app. I couldn't figure out why for the life of me this was happening. I thought it was because I upgraded jquery.mobile. That wasn't it. I then thought it was an .htaccess issue, that wasn't it either. It turns out, it was Cordova 2.7 that was causing this problem.
I did try adding the .json file on my server, that did not fix the issue.
The fix was going into the 2.7 source and commenting out the following code:
/*comment out this as it is breaking console.logs
var xhr = new context.XMLHttpRequest();
xhr.onload = function() {
// If the response is a JSON string which composes an array, call handlePluginsObject.
// If the request fails, or the response is not a JSON array, just call finishPluginLoading.
var obj = this.responseText && JSON.parse(this.responseText);
if (obj && obj instanceof Array && obj.length > 0) {
handlePluginsObject(obj);
} else {
finishPluginLoading();
}
};
xhr.onerror = function() {
finishPluginLoading();
};
xhr.open('GET', 'cordova_plugins.json', true); // Async
xhr.send();
*/
Replace entire block with a call to the following function:
finishPluginLoading();
My logs are now working again. Only took me 3 days scratching my head.
Hope this helps someone with a similar problem.
If you embed Cordova in the external web page, there will be no way to open the InAppBrowser from within your hybrid app, so Cordova will not be able to load. This is because the InAppBrowser requires Cordova to be fully loaded and initialized before it can be used to fetch a remote page. You need to use your HTML page that you have, with the <script type="text/javascript" src="http://mydomain.com/mobile/cordova-2.7.0.js"></script> as the main entry point for your app. Then you can use the InAppBrowser to open up your remote page. (You could probably do this in the onDeviceReady(), not sure if it would "flash" the page first though.) I don't think the remote page should have any Cordova code in it at all. I'm not sure if it would be possible to even interact with Cordova from the remote page due to the Same Origin Policy (probably you could use features of the InAppBrowser to inject "bridge" code though to get around this.)
As Shazron mentioned the problem is the issue with the file"cordova_plugins.json".
To solve the problem not changing the code you can create the "cordova_plugins.json" file in the root folder and insert a content between quotation marks inside this file.
Mine for example has the following content:
"Just a dummy file required since Cordova 2.6.0"
create a file cordova_plugins.json that contains {}. then go to cordova-2.7.0.js and comment this line require('cordova/channel').onNativeReady.fire(); then when development done, add it back
Like me if you are using Cordova 5.1.1 and want to access native functionality after redirect then copy cordova.js, cordova_plugins.js and plugins folder which is at \platforms\platform_name\assets\www\ and put them on server, finally reference cordova.js inside your html. After every plugin add make sure to update these files and folder.

titanium webview fireEvent addEventListener

here's my situation. I have a html +css + jquery well working project that I want to adapt in titanium. This project has geolocation + fb api call.
I want to adapt my project into a titanium html5 project. What I found is that I can call titanium api only through addEventListener and fireEvent functions (of course only if I use webviews).
it' my first titanium project I work with that needs geolocation and facebook api.
actually, I started to modify the previous project by adding addEventlistener into the app.js file and fireEvents into the javascript files of the previous project ( included in the first project in the html files) in the parts that need the titanium api calls (I can't call titanium api outside of app.js).
the problem is that I need some values (objects) to be returned back.
to better understand what I'm doing, here's the sequence of the events.
TITANIUM PROJECT
(app.js)
var win = Ti.UI.createWindow();
var webview = Ti.UI.createWebView({
url: 'index.html'
});
Ti.App.addEventListener('geolocation',function(){
//some titanium api call
lat = x;lon=y;
Ti.App.fireEvent('geolocation_back',{latitude:lat,longitude:lon});
});
win.add(webview);
win.open();
HTML + CSS + JS PROJECT
(imported file into index.html, not imported into app.js)
Ti.App.fireEvent('geolocation');
var my_lat ;
var my_lon ;
Ti.App.addEventListener('geolocation_back',function(d){
my_lat = d.latitude;
my_lon = d.longitude;
//do other stuff with my_lat and my_lon
});
I hope you understand what I'm doing.
my questions are:
1) is what I am doing the correct way to work with titanium and html code?
2) is there anyother way to call titanium api within html code and return variables/objects back?
EDIT
this code works only on iOS and android but not on web browser. it seems that the built in server (Titanium studio or Android web browser emulator) doesn't load the Ti.* or Titanium.* objects. is there anyway to make it works on web browser?
I see the web mobile compiler creates all the titanium API in subfolders
there is titanium.js and TI/* folder. can anyone explains me why the console says me Ti is not defined?
as I said here
I found a solution!
simply add to all of your html pages the simple script below
var Ti = window.parent.Ti
have fun!

Categories