I am using JavaScript web worker technique inside UIWebView HTML pages to achieve background tasks in Titanium apps. It works fine on iOS but no luck on Android, I can't even figure out the error details. Here's the script code:
<script>
function startWorker(){
var worker = new Worker('/worker.js');
// message event handler
worker.onmessage = function (event) {
// logging
Ti.API.error( 'WebWorkerMessage:'+ JSON.stringify(event) );
// update the html page - not actually needed, just for demostration should the WebView be visible
document.getElementById('result').textContent = event.data;
// fire a titanium app event
Ti.App.fireEvent( "WORKER", { data: event.data } );
};
// error event handler
worker.onerror = function(event){
Ti.API.error( 'WebWorkerError:'+ JSON.stringify(event) );
};
}
</script>
The error handler is called as soon as this script is evaluated from my Alloy controller. I am testing this script on an Android 4.4.2 device, a log for this error is useless:
WebWorkerError:{"cancelBubble":false,"returnValue":true,"srcElement":{},"defaultPrevented":false,"timeStamp":1422484158088,"cancelable":true,"bubbles":false,"eventPhase":2,"currentTarget":{},"target":{},"type":"error"}
Any suggestions?
Related
I have recently built a Chrome Extension that is coupled with a service worker, which recives push notifications via FCM, this is all working and my Service worker triggers correctly.
I want to be able to set the Chrome Extension Badge text from this function, as my server is updating the extension with the correct count.
Here is the function that I am currently using.
self.addEventListener('push', function(event) {
if (event.data) {
let data = event.data.json();
if (data.count){
// This is the only function that I can see when I debug the chrome obj
chrome.runtime.getBackgroundClient().then((bgClient) => {
console.log(bgClient)
})
}
}
});
I am aware of the
chrome.browserAction.setBadgeText({text: count});
function but this does not seem to be available from within the service worker, not can I see a way of accessing my background scripts.
I'm enabling web notification to my web site and added below event listener to service worker .js file,
This works fine in edge and click event gets trigger and opens a new window, however chrome nothing happens and event it self does not trigger -
self.addEventListener('notificationclick', function (event) {
event.notification.close();
console.log('Notification notificationclick triggered');
event.waitUntil(
clients.openWindow(event.notification.data)
);
})
Just tested it on Chrome and its working as intended:
self.addEventListener('notificationclick', function (event) {
clients.openWindow("/");
});
Unregister your Service Worker using the Chrome devs window then find the Application tab. You would be able to update or unregister that particular service.
Looks like you need to do that in order to see the changes you made to the file from time to time. Maybe browser cache or so.
You can use data object in place of notification.
eg.
{
"to": "pass token here",
"data":{
"title": "Hello",
"body": "Good Evening",
"click_action":"https://stackoverflow.com/"
}
}
Turn off your adblocker! Spent 2 hours trying to debug this.After that try registering your service worker again.
I have an app that could go in to offline mode. For that i have implemented a HostListener which listens to apps events.
#HostListener('window:offline', ['$event']) onOffline() {
this.isOnline = false;
}
This works fine and I display an error message:
<div *ngIf="!isOnline">
<div class="network-div">
<mat-icon class="network-icon">cloud_off</mat-icon>
</div>
<p class="network-text">Network error - unable to connect.
Please try again or contact support if error persists, contact the NCR
support desk.</p>
</div>
When i go offline, i get the desired message, but now that internet is down, when i refresh, I get the usual google error message with that dinasour.
I can't render the error HTML in my angular component anymore since its running in offline mode. I need to render the above HTML when i refresh.
When i click on 'Offline' of developer tool, i render an HTML and below is the screenshot:
When i refresh the same page (still in offline mode),i receive the following:
How should i handle this?
if you are registering service worker you can try:
ngOnInit() {
if (!navigator.onLine) {
this.isOnline = false;
}
}
note that you should check it after build your project and serve it.
About the browser's cache visit: How to Enable Offline Browsing in Firefox
If you attach the event listener to document.body on a browser, Chrome couldn't work.
You can register listeners for these events:
using addEventListener on the window, document, or document.body
by setting .onoffline properties on document or document.body to a
JavaScript Function object.
by specifying onoffline="..."
attributes on the tag in the HTML markup.
A javascript
window.addEventListener('load', function() {
var status = document.getElementById("status");
var log = document.getElementById("log");
function updateOnlineStatus(event) {
var condition = navigator.onLine ? "online" : "offline";
status.className = condition;
status.innerHTML = condition.toUpperCase();
log.insertAdjacentHTML("beforeend", "Event: " + event.type + "; Status: " + condition);
}
window.addEventListener('online', updateOnlineStatus);
window.addEventListener('offline', updateOnlineStatus);
});
Go to the networks tab in your developer tools and see if the SW is registered and offline works by running Audit.
In article about notifications Mozzila says:
Note: This feature is available in Web Workers.
Worker can be created without any warnings
var worker = new SharedWorker('scripts/worker.js');
But when I try to do this inside shared worker:
var notification = new Notification("Hi there!");
It doesn't work. Webworker works fine, it does a XMLHttpRequest, it can read data from main thread and push messages to it but notification doesn't appear. I can't debug it because console is unavailable inside webworker. Permission was granted in main thread and the notifications are also available here.
If it is important I use Chrome 47.0.2526.111 m for developing and debugging. I noticed that Facebook invokes notifications even when FB tab is closed so I am trying to implement something similar.
You are doing something wrong. I had absolutely no problems running notifications in web workers.
This code works perfectly on jsfiddle:
Worker example
SharedWorker example
Please try following code:
main.js
var worker = new SharedWorker("worker.js");
worker.port.start();
Notification.requestPermission(function (permission) {
// If the user accepts, let's create a notification
if (permission === "granted") {
worker.port.postMessage({name:"notification"});
}
});
worker.js
function workerFN() {
function onmessage(e) {
switch(e.data.name) {
case "notification" :
console.log("Notification:");
var notification = new Notification("Hi there!");
break;
default:
console.error("Unknown message:", e.data.name);
}
}
self.onconnect = function(e) {
for(var i=0,l=e.ports.length; i<l; i++) {
e.ports[i].addEventListener('message', onmessage);
e.ports[i].start(); // Required when using addEventListener. Otherwise called implicitly by onmessage setter.
}
}
}
Also console works quite well for me in web workers.
I have a simple Titanium app which opens a webview, and loads a URL. I want the links to open in the default browser, not the app.
I have some jQuery code which adds a click event to all links in the page.
<script>
jQuery('a').click(function() {
console.log("Handler for .click() called for URL: " + this.href);
Ti.App.fireEvent('ynOpenURL', {url: this.href });
});
In the app.js file I have:
var win = Ti.UI.createWindow();
var mywebview = Ti.UI.createWebView({
url : 'http://xxxx.xxxxx.com/',
enableZoomControls: false
});
win.add(mywebview);
win.open();
Ti.App.addEventListener('ynOpenURL', function(e) {
Ti.API.info('yyyyyy');
Ti.API.info(e.url);
if (Ti.Platform.canOpenURL(e.url)){
Ti.Platform.openURL(e.url);
} else {
alert("Cannot open URL");
}
When I run the app on my Android (4.4) the web page loads correctly.
When I click a link on the phone I get the following in the console:
Handler for .click() called for URL: http://xxx.xxxxx.xxx/
Uncaught TypeError: Cannot read property 'App' of undefined (xxxx)
None of the Titanium console events are logged, only the javascript events in the webpage.
As you mentioned that the webview is loading remote url. So Ti.* or Titanium.* are not available at your remote server.
What you can do is :
Create a html file within the app and load the data via ajax and use fireEvent.
Load the data via titanium http client and use Ti.Platform.openURL accordingly.
Edit : Quote from Titanium WebView Docs
Remote Scripts
Scripts downloaded from remote web servers cannot access the Titanium namespace.
To interact with remote content, wait until the content is loaded, then use the evalJS method to execute a JavaScript expression inside the web view and retrieve the value of an expression.