Javascript Google Maps API & non-passive event handlers - addeventlistener

Recently Chrome started emitting the following warnings:
[Violation] Added non-passive event listener to a scroll-blocking 'touchmove' event. Consider marking event handler as 'passive' to make the page more responsive. See https://www.chromestatus.com/feature/5745543795965952
These are coming from the JavaScript Google Maps API code. I'm able to add {passive: true} to addEventListener() in my own code but don't know how to suppress the warning in Googles libraries?

this works for me. Got here https://stackoverflow.com/a/55388961/2233069
(function () {
if (typeof EventTarget !== "undefined") {
let func = EventTarget.prototype.addEventListener;
EventTarget.prototype.addEventListener = function (type, fn, capture) {
this.func = func;
if(typeof capture !== "boolean"){
capture = capture || {};
capture.passive = false;
}
this.func(type, fn, capture);
};
};
}());

There is nothing you can do at this point. It's a warning that is generated from Googles own API code. As long as your own event listeners are passive, I think it can be safely ignored.

Related

Service Worker caching not recognizing timeout as a function

I was watching Steve Sanderson's NDC presentation on up-and-coming web features, and saw his caching example as a prime candidate for an application I am developing. I couldn't find the code, so I have typed it up off the Youtube video as well as I could.
Unfortunately it doesn't work in Chrome (which is also what he is using in the demo) It fails with Uncaught TypeError: fetch(...).then(...).timeout is not a function
at self.addEventListener.event.
I trawled through Steve's Github, and found no trace of this, nor could I find anything on the NDC Conference page
//inspiration:
// https://www.youtube.com/watch?v=MiLAE6HMr10
//self.importScripts('scripts/util.js');
console.log('Service Worker script running');
self.addEventListener('install', event => {
console.log('WORKER: installing');
const urlsToCache = ['/ServiceWorkerExperiment/', '/ServiceWorkerExperiment/scripts/page.js'];
caches.delete('mycache');
event.waitUntil(
caches.open('mycache')
.then(cache => cache.addAll(urlsToCache))
.then(_ => self.skipWaiting())
);
});
self.addEventListener('fetch', event => {
console.log(`WORKER: Intercepted request for ${event.request.url}`);
if (event.request.method !== 'GET') {
return;
}
event.respondWith(
fetch(event.request)
.then(networkResponse => {
console.log(`WORKER: Updating cached data for ${event.request.url}`);
var responseClone = networkResponse.clone();
caches.open('mycache').then(cache => cache.put(event.request, responseClone));
return networkResponse;
})
//if network fails or is too slow, return cached data
//reference for this code: https://youtu.be/MiLAE6HMr10?t=1003
.timeout(200)
.catch(_ => {
console.log(`WORKER: Serving ${event.request.url} from CACHE`);
return caches.match(event.request);
})
);
});
As far as I read the fetch() documentation, there is no timeout function, so my assumption is that the timeout function is added in the util.js which is never shown in the presentation... can anyone confirm this? and does anyone have an Idea about how this is implemented?
Future:
It's coming.
According to Jake Archibald's comment on whatwg/fetch the future syntax will be:
Using the abort syntax, you'll be able to do:
const controller = new AbortController();
const signal = controller.signal;
const fetchPromise = fetch(url, {signal});
// 5 second timeout:
const timeoutId = setTimeout(() => controller.abort(), 5000);
const response = await fetchPromise;
// …
If you only wanted to timeout the request, not the response, add:
clearTimeout(timeoutId);
// …
And from another comment:
Edge & Firefox are already implementing. Chrome will start shortly.
Now:
If you want to try the solution that works now, the most sensible way is to use this module.
It allows you to use syntax like:
return fetch('/path', {timeout: 500}).then(function() {
// successful fetch
}).catch(function(error) {
// network request failed / timeout
})

ngCordova InAppBrowser plugin freeze app on iOS but no on Android

I am currently using, IONIC v1.0.0, AngularJs and ngCordova v0.1.23-alpha on IOS and Android.
I have come across an issue with my login view freezing up.
It happens after opening InAppBrowser and hitting "back to app" (close button caption used for IOS to get back) is freezes my login view disabling the ability to touch on the whole screen and making me unable to login. It only happens if I call InAppBrowser when starting the app, if I use it during the app life cycle (after login in), it doesn't do it.
Here are some of my code pieces
In app.js:
angular.module('MyApp', ['ionic', 'MyApp', 'ngCordova', 'mainController', 'loginController', 'pascalprecht.translate', 'ngStorage', 'ngSanitize', 'ngAnimate', 'ngTouch', 'ngCookies', 'ngLocale', 'testController'])
In mainController I have Factory:
.factory('customMainFunction', function ($rootScope, $ionicLoading, $ionicScrollDelegate, $ionicPopup,
$timeout, $localStorage, $location, $ionicHistory, $window, $cordovaInAppBrowser) {
var Token = "";
return {
openBrowser: function (link) {
var options = {
location: 'yes',
clearcache: 'yes',
toolbar: 'yes',
closebuttoncaption: 'Back to App'
};
document.addEventListener("deviceready", function () {
$cordovaInAppBrowser.open(link, '_blank', options)
.then(function (event) {
// success
})
.catch(function (event) {
// error
});
}, false);
$rootScope.$on('$cordovaInAppBrowser:loadstart', function (e, event) {
//console.log(event);
var url = "";
var positionNumber;
var res;
url = event.url;
positionNumber = url.search("ssoToken=");
res = url.substr(Number(positionNumber)+9);
/*positionNumber = url.search("module=");
res = url.substr(Number(positionNumber)+6);*/
if(url !== "" && positionNumber >= 0 && res.length > 0) {
$rootScope.$broadcast('ssoToken', { token: res });
$cordovaInAppBrowser.close();
}
});
$rootScope.$on('$cordovaInAppBrowser:loadstop', function (e, event) {
console.log("loadstop");
//console.log(event);
// insert CSS via code / file
//$cordovaInAppBrowser.insertCSS({
// code: ''
//});
// insert Javascript via code / file
//$cordovaInAppBrowser.executeScript({
// file: ''
//});
});
$rootScope.$on('$cordovaInAppBrowser:loaderror', function (e, event) {
});
$rootScope.$on('$cordovaInAppBrowser:exit', function (e, event) {
});
}
}
})
If anybody has encounter such issue please let me know what can be done to resolve it. Any question or clarifications let me know. Thanks in advance.
Found the issue of my own problem. Basically the problem is related to Threading. Look for Threading. How did I find out about it? On XCode I was able to see a message saying:
THREAD WARNING: ['InAppBrowser'] took '108.12' ms. Plugin should use a
background thread
There are two ways to solve this (I believe):
1- Using background threading (just like the message states). Please refer to:
How to run cordova plugins in the background?
2- Wrap the openBrowser function call (in my case) in a setTimeout. That will delay the call until the thread is done and UI won't be blocked. Once done (in my case) it opened the inAppBrowser and when I hit "Back to app" UI was not block at all.
Hope this helps someone out there.

Can I listen for a XUL type event in the add-on SDK

I am trying to listen for the event which occurs when an "Authorisation Required" dialogue is displayed (see Firefox Addon SDK Hotkeys and contect menu options dont work on Authentication Required Popup).
However I notice that XUL addons can listen for a DOMWillOpenModalDialog event which is apparently triggered when this dialogue box opens. None of the SDK panel events seem to be triggered.
Is there a way to listen for this event from within the addon SDK?
------Edit------
Going on from Noitidart 's sugestion I then tried a couple of other events and they fire. Both the attempts below work.
var events = require("sdk/system/events");
function listener(event) {console.log("An event popup was activated.");}
events.on("xul-window-visible", listener);
CWin.addEventListener("DOMWillOpenModalDialog", function() {CWin.setTimeout(NfyBox, 500);}, true);
function NfyBox() {
console.log("An event popup was activated.");
worker = tabs.activeTab.attach({
contentScriptFile: self.data.url("notifybox.js")
});
worker.port.emit("notify");
}
However that is as far as I get, in the contentScriptFile, a console.log of document produces :-
console.log: infstr: {"location":{"assign":"function assign() {\n [native cod
e]\n}","replace":"function replace() {\n [native code]\n}","reload":"function
reload() {\n [native code]\n}","toString":"function toString() {\n [nativ
e code]\n}","valueOf":"function valueOf() {\n [native code]\n}","href":"http:
//c1s4-1e-syd.hosting-services.net.au:2082/unprotected/redirect.html","origin":"
http://c1s4-1e-syd.hosting-services.net.au:2082","protocol":"http:","username":"
","password":"","host":"c1s4-1e-syd.hosting-services.net.au:2082","hostname":"c1
s4-1e-syd.hosting-services.net.au","port":"2082","pathname":"/unprotected/redire
ct.html","search":"","hash":""}}
But an attempt to get getElementById or anything else I tried comes back undefined. I am obviously making some simple mistake, but can’t see what it is.
Yes listen to popup events. In this case popupshowing: MDN : PopupEvents
This is an example that prevents the main menu at top right (tri stripe menu button) from closing by listening to popuphiding and preventing it:
var PUI = Services.wm.getMostRecentWindow('navigator:browser').document.querySelector('#PanelUI-popup');
try {
PUI.removeEventListener('popuphiding', previt, false);
} catch (ignore) {}
var previt = function(e) {
PUI.style.opacity = 1;
e.stopPropagation();
e.preventDefault();
e.returnValue = false;
return false;
}
PUI.addEventListener('popuphiding', previt, false);

External link in WinJS, iframe or not, doesnt matter

I work on a Windows 8 app, and from a page that I use link hystory for running back and forward through the app, I also have 3 or 4 links to external websites(eg: facebook or my site). I tried to run them in iframe, or also to make them open in the default browser like simple links. Both method resulted in an error in base.js that says it can't handle my error (!?) I searched a lot before asking here. I watched msdn sample that works just fine, but if i copy what I need in my app results in the same error. I I use it from another page where I dont have forward history, it works, but i really need it on the front page. Any ideeas? Thank you very much.
LE:
This is my items.js code: ( for the items.html page )
(function () {
"use strict";
var appViewState = Windows.UI.ViewManagement.ApplicationViewState;
var ui = WinJS.UI;
ui.Pages.define("/pages/items/items.html", {
// This function is called whenever a user navigates to this page. It
// populates the page elements with the app's data.
ready: function (element, options) {
var listView = element.querySelector(".itemslist").winControl;
listView.itemDataSource = Data.groups.dataSource;
listView.itemTemplate = element.querySelector(".itemtemplate");
listView.oniteminvoked = this._itemInvoked.bind(this);
this._initializeLayout(listView, Windows.UI.ViewManagement.ApplicationView.value);
listView.element.focus();
WinJS.Utilities.query("a").listen("click", this.linkClickEventHandler, false);
},
// This function updates the page layout in response to viewState changes.
updateLayout: function (element, viewState, lastViewState) {
/// <param name="element" domElement="true" />
var listView = element.querySelector(".itemslist").winControl;
if (lastViewState !== viewState) {
if (lastViewState === appViewState.snapped || viewState === appViewState.snapped) {
var handler = function (e) {
listView.removeEventListener("contentanimating", handler, false);
e.preventDefault();
}
listView.addEventListener("contentanimating", handler, false);
var firstVisible = listView.indexOfFirstVisible;
this._initializeLayout(listView, viewState);
if (firstVisible >= 0 && listView.itemDataSource.list.length > 0) {
listView.indexOfFirstVisible = firstVisible;
}
}
}
},
linkClickEventHandler: function (eventInfo) {
eventInfo.preventDefault();
var link = eventInfo.target;
WinJS.Navigation.navigate(link.href);
},
// This function updates the ListView with new layouts
_initializeLayout: function (listView, viewState) {
/// <param name="listView" value="WinJS.UI.ListView.prototype" />
if (viewState === appViewState.snapped) {
listView.layout = new ui.ListLayout();
} else {
listView.layout = new ui.GridLayout();
}
},
_itemInvoked: function (args) {
var groupKey = Data.groups.getAt(args.detail.itemIndex).key;
WinJS.Navigation.navigate("/pages/split/split.html", { groupKey: groupKey });
}
});
})();
And from items.html I have different types of links: some of them links to other application pages, from where I can return with history buttons back/forward and some of them are links to external page. Simple link.These links crashes my app with the error that I mentioned below. If I erase the next line:
WinJS.Utilities.query("a").listen("click", this.linkClickEventHandler, false);
from my js script, external links works, but I dont have anymore history buttons in my others's app pages.
You are trying to use the navigation framework to navigate to an external URI. It's usually meant to be used within the application's local context and pages that can contain 'fragments' to load up into your main nav control.
I wouldn't hook anchor tags with your function call, instead in your linkClickEventHandler I would do the following to only hook your internal links
WinJS.Utilities.query(".nav").listen("click", linkClickEventHandler, false);
in turn your internal links would be
click me
This approach only hooks the navigation framework into your internal links. Another approach is to inspect the 'this.href' in your handler and if it contains http:// or https:// then call window.open instead

no device ready and no console.log with xcode using cordova 1.5

This is all the code I have and I do not get neither the logs in xcode nor the deviceReady event (which I don't get on any other platform either. On Ubuntu+Android+Eclipse I do get the console logs, but no deviceReady. nor in chrome )
The js/cordova-1.5.0.js exists and being loaded as indicates an alert statement i've put in there.
Any clues where should I look ?
Thanks in advance ;)
<div id="d"></div>
<script>
function foo() {console.log('test'); document.getElementById('d').innerHTML += 'called';}
window.setTimeout(foo, 5000);
window.setTimeout(foo, 15000);
window.setTimeout(foo, 25000);
window.setTimeout(foo, 35000);
alert('hi');
console.log('non timed console.log');
</script>
<script src="js/cordova-1.5.0.js"></script>
<script>
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
alert('deviceReady');
//somewhy this never happens
}
</script>
Console.log works only after deviceReady event
Phonegap uses different phonegap.js files for android and ios, and only the
android one is distributed with the downloadable archive. Read
Dhaval's comment to learn where to get the ios version.
I used Weinre for debugging and almost missed that it overrides the console.log method,
therefore console.log doesn't work with weinre
As Alex pointed out, console.log is not available until after your PhoneGap device is ready. By calling it too soon, you're triggering a reference error.
Remove ALL of your existing javascript, and try this instead (replacing the alert on the second-last line with your own custom code):
var app = {
// denotes whether we are within a mobile device (otherwise we're in a browser)
iAmPhoneGap: false,
// how long should we wait for PhoneGap to say the device is ready.
howPatientAreWe: 10000,
// id of the 'too_impatient' timeout
timeoutID: null,
// id of the 'impatience_remaining' interval reporting.
impatienceProgressIntervalID: null,
// Application Constructor
initialize: function() {
this.bindEvents();
},
// Bind Event Listeners
//
// Bind any events that are required on startup. Common events are:
// `load`, `deviceready`, `offline`, and `online`.
bindEvents: function() {
document.addEventListener('deviceready', this.onDeviceReady, false);
// after 10 seconds, if we still think we're NOT phonegap, give up.
app.timeoutID = window.setTimeout(function(appReference) {
if (!app.iAmPhoneGap) // jeepers, this has taken too long.
// manually trigger (fudge) the receivedEvent() method.
appReference.receivedEvent('too_impatient');
}, howPatientAreWe, this);
// keep us updated on the console about how much longer to wait.
app.impatienceProgressIntervalID = window.setInterval(function areWeThereYet() {
if (typeof areWeThereYet.howLongLeft == "undefined") {
areWeThereYet.howLongLeft = app.howPatientAreWe; // create a static variable
}
areWeThereYet.howLongLeft -= 1000; // not so much longer to wait.
console.log("areWeThereYet: Will give PhoneGap another " + areWeThereYet.howLongLeft + "ms");
}, 1000);
},
// deviceready Event Handler
//
// The scope of `this` is the event. In order to call the `receivedEvent`
// function, we must explicity call `app.receivedEvent(...);`
onDeviceReady: function() {
app.iAmPhoneGap = true; // We have a device.
app.receivedEvent('deviceready');
// clear the 'too_impatient' timeout .
window.clearTimeout(app.timeoutID);
},
// Update DOM on a Received Event
receivedEvent: function(id) {
// clear the "areWeThereYet" reporting.
window.clearInterval(app.impatienceProgressIntervalID);
console.log('Received Event: ' + id);
myCustomJS(app.iAmPhoneGap); // run my application.
}
};
app.initialize();
function myCustomJS(trueIfIAmPhoneGap) {
// put your custom javascript here.
alert("I am "+ (trueIfIAmPhoneGap?"PhoneGap":"a Browser"));
}
I know the question was asked 9 month before but I stumbled over the same problem.
If you want debug messages to appear in the weinre console you have to call:
window.cordova.logger.useConsole(false);
after deviceready.
Update:
It seems that you need luck to get console messages into weinre - thats bad :(

Resources