Register gcm for chrome - javascript

I have a chrome Apps use push notification of GCM. I have a problem, when i don't login account on chrome. I can't receive registerId from GCM. I think a idea. When registerId empty, i show notification, request user login to chrome and show login page account on chrome. But because of security concerns , the chrome does not allow access to its setting from external links . How is open "chrome://settings/" from external links? Can register to gcm, If i don't want login account on chrome?
My code:
function setValue()
{
//var thongtin=$('#status').val();
//var thongtin = document.getElementById('status').innerText;
if(registrationId == "")
{
// Pop up a notification to show notification.
chrome.notifications.create(getNotificationId(), {
title: 'CLOUD MONITOR',
iconUrl: 'gcm_128.png',
type: 'basic',
message: 'You must sign in account gmail on google chrome!'
}, function() {});
//event click to notification
chrome.notifications.onClicked.addListener(function() {
window.location.href = "chrome://settings/"
});
}
else
{
//http://mtraffic.longvan.net/device_register?regId=" +registrationId+"&device=android
//document.getElementById('webviewSendData').src = "http://192.168.64.246:8080/register?REGID=" +registrationId+"&DEVICE=desktop";
document.getElementById('webviewSendData').src = "http://mtraffic.longvan.net/device_register?regId="+registrationId+"&device=android";
//document.getElementById('webviewSendData').src = "http://192.168.64.124:8080/monitor/device_register?regId=" +registrationId+"&device=android";
//var url = "http://192.168.64.124:8080/monitor/device_register?regId=" +registrationId+"&device=android";
//httpGet(url);
//alert(thongtin);
//document.getElementById('status').innerHTML="Infomation New";
// Pop up a notification to show notification.
}
}
This code don't run.
chrome.notifications.onClicked.addListener(function() {
window.location.href = "chrome://settings/"
});
I fix code as Derek 朕會功夫.
chrome.notifications.onClicked.addListener(function() {
chrome.tabs.create({url: "chrome://settings/"});
});
And receive error notify: Error in event handler for notifications.onClicked:TypeError: Can't read property 'create' of underfined.

I'm afraid at the moment it's not possible.
Chrome Apps don't have access to tabs/windows API that can open privileged pages; that's why Derek's suggestion does not work.
In future, they may be a way to do this with chrome.browser API. See this feature request, this proposal, and please leave feedback there with your use case.

Related

Chrome, allow autoconnect for HID device

So I'm trying to read out a USB-scale thats connected to my pc. I use chrome's experimental HID api.
I use Tampermonekey as userscript injector to extend a website's functionality.
The script I inject looks like this:
navigator.hid.requestDevice({ filters: [{ vendorId: 0x0922, productId: 0x8003}] }).then((devices) => {
if (devices.length == 0) return;
devices[0].open().then(() => {
if(disconnected) {
disconnected = false
}
console.log("Opened device: " + devices[0].productName);
devices[0].addEventListener("inputreport", handleInputReport);
devices[0].sendReport(outputReportId, outputReport).then(() => {
console.log("Sent output report " + outputReportId);
});
});
});
When I run it just like this(inline) I get the message in chrome:
DOMException: Failed to execute 'requestDevice' on 'HID': Must be handling a user gesture to show a permission request.
Basically, the code needs to be inside an event listener and the listener needs to be triggered by user input to run.
Al fine and dandy, except that this has to be initialized hundreds of times a day. I tried running this code in edge and here it just works without user input.
Is there a way I can disable this security feature(completely or only for the site im using it on) in chrome? I know edge is based on chromium so I expect it to be possible, but am unable to find how/where
You can use HID.getDevices() to retrieve an HID device that the user has already granted access to.
My suggestion would be to check for the device you want with getDevices first. If you can't find the device, then make something the user can interact with that will allow you to use requestDevice to connect to the device.

Not allowed to launch cutom protocol because a user gesture is required

I need to run my custom protocol twice but it doesn't work the second time, I got this error ( Not allowed to launch 'cutomProtocol' because user gesture is required. ) I tried to find a solution but I did not find any!
Same problem with chrome, firefox and edge.
I need to see this popup twice
window.location.href = 'my-protocol://${base64}';
and
customProtocolVerify(
`my-protocol://${base64}`,
() => {
// successCb: Callback function which gets called when custom protocol is found.
console.log('My protocol found and opened the file successfully..');
},
() => {
// failCb: Callback function which gets called when custom protocol not found.
console.log('My protocol not found.');
}
);
I tried with these two and didn't work
Clarification
I have a custom protocol.
My scenario:
check if it's installed successfully (I'm using customProtocolVerify method) and that method makes the launch if the protocol is found
run some APIs
launch the protocol again
My problem:
Step 3 doesn't work, I have the error on the console that says " Not allowed to launch... " and of course I can't see my popup to open my protocol.
I'm asking for help to make step 3 work
The only way to bypass this "bug" is to ask the user twice (or in a loop) by showing a OK alert or some sort of user confirm box.
My solution:
OpenLinkInExternalApp(Link);
alerty.alert('', { title: '', okLabel: 'Open Link' }, function () {
OpenLinkInExternalApp(Link);
});
The above code will open the external app, then a OK alert will pop up, after clicking OK, I call the same code again. Do this in a loop if needed.
TIP:
We guide our users to use split screen at this stage. This is where users can dock your web-app on the left and the external app on the right as an example.
Alert Box:
We user Alerty.js https://github.com/undead25/alerty#readme

service worker notificationclick event doesn't focus or open my website in tab

I use FCM push notification in my website and I want user can come into my website when He or She clicks on the push notification. Please notes that The user may be in other app or in other browser tab and I want when the user gets fcm notification the user will be able to come into my website by a click on the notification in the Firefox browser. For this reason, I used notificationclick event which Is available in the service worker. The code that I used is this:
self.addEventListener('notificationclick', event => {
console.log('On notification click: ', event.notification.tag);
event.notification.close();
// This looks to see if the current is already open and
// focuses if it is
event.waitUntil(
clients
.matchAll({
type: 'window'
})
.then(clientList => {
for (let i = 0; i < clientList.length; i++) {
const client = clientList[i];
if (client.url === '/' && 'focus' in client) return client.focus();
}
if (clients.openWindow) return clients.openWindow('/');
})
);
});
It doesn't openwindow or focuses on my website tab. To debug the code I printed the clientList variable and It is an array with zero length.
The error that I get in the browser is this
On notification click:
InvalidStateError: An attempt was made to use an object that is not, or is no longer, usable firebase-messaging-sw.js:92
The above error refers to this line of code:
event.waitUntil(
OS: Mac
firefox:63.0.3
reactjs:16.2.0
Move your notificationclick handler BEFORE your line of code with messaging = firebase.messaging();. The FCM JS SDK installs its own global notificationclick handler and its e.waitUntil() call manages to (somehow) break the Firefox event object. If you install your global handler first, then it gets called first and so it will actually work. However, it will probably break the FCM handler in some obscure fashion.
This is, IMO, a bug in Firefox itself with regards to Service Workers rather than FCM, but FCM certainly contributes to the problem.
Relevant:
https://github.com/firebase/quickstart-js/issues/282 (same FCM bug)
https://bugzilla.mozilla.org/show_bug.cgi?id=1468935 (same FCM + Firefox bug, bad fix)
https://bugzilla.mozilla.org/show_bug.cgi?id=1313096 (the Firefox dev team doesn't have a way to test the callback in its Service Worker test suite, which makes this part of Firefox ripe for bugs)
https://bugzilla.mozilla.org/show_bug.cgi?id=1489800 (same browser bug, different product)
If the goal is to open a specific URL when the notification is clicked, there may be an easier way. You can sent a "click_action" field in the FCM notification payload.
Your payload would look something like this:
"notification" : {
"body" : "Sample body",
"title" : "Sample title",
"click_action": "http://google.com"
}
And when the notification is clicked, it will open google.com in this example.

Firebase Cloud Messaging: Prevent background notifications in javascript client

I have a live score display website which is implemented with Google's channel API to push live score updates to the browser. Since Google is shutting down the channel API, I have to move to Firebase Cloud Messaging.
When I migrated to FCM, I had to add a service worker javascript file (firebase-messaging-sw.js). Whenever a score update is pushed to the browser, if the user is in another browser tab or the user has closed my web page tab, A notification appears to the user.
I don't need this notification and I want to disable it. Also, when user moves to another browser tab, I want to prevent the push message from going into the service worker and route it to my web page, so that when user returns to the tab again, the latest score is updated in the webpage.
Is there any way to achieve this?
You should pass a parameter (depends what you need to do) in the body of message like this:
$msg = [
'title' => pushTitle,
'body'=> pushBody,
'icon'=> icon.png,
'image'=> image.png,
'active'=> 1
];
The above is PHP but is also working in the same way-idea in any programming language. If you use Firebase then you should use cloud functions.
then in your js file:
messaging.setBackgroundMessageHandler(function(payload) {
console.log('Received background message', payload);
if(payload.data.active == 1){
return;
}
var notificationTitle = payload.data.title;
var notificationOptions = {
body: payload.data.body,
icon: payload.data.icon,
image: payload.data.image
};
return self.registration.showNotification(notificationTitle, notificationOptions);
});
If I had your code(what did you have done until now) I would gave you an exact answer.
If you have more questions don't hesitate to ask.

ADAL.JS and Offline Web App

I have a web page where I implement ADAL.JS.
When browsing the page via the web it works perfectly; however when I try to view it on an iPhone, and I have saved it as a shortcut on the desktop using the Add to Homescreen button, things go haywire.
The initial page (index.html) shows correctly using the apple-mobile-web-app-capable meta tag; however, when the authentication is invoked, I am taken to a real browser window. Once redirected back to index.html, I am still in the separate browser window not the Web App view.
Ultimately, I want to have this as an offline web site with all page functionality running in the view produced by apple-mobile-web-app-capable. Any other ideas as to how to implement this are appreciated.
Thanks in advance.
This is one of the big problems currently existing in iOS webapps. Every link or redirection opens up in a new window.
You can fix it changing window.location.href with JavaScript.
Seem to be missing something...I get at urlNavigate not defined error...suggestions?
alert('Running Auth');
online = navigator.onLine;
authContext = new AuthenticationContext({
tenant: azureTenant,
clientId: azureClientId,
postLogoutRedirectUri: window.location,
//redirectUri: "https://shlpkpiapi.azurewebsites.net/kpiapp/test.html"
});
authContext.config.displayCall=function(url){
if (urlNavigate)
{
this.info('Navigate to:' + urlNavigate);
window.location.href=urlNavigate;
}
else
{
this.info('Navigate url is empty');
}
}
if (authContext.isCallback(window.location.hash)) {
authContext.handleWindowCallback();
var err = authContext.getLoginError();
if (err) {
alert('Error on callback')
}
}
else {
var user = authContext.getCachedUser();
if (user) {
//We have a user in cache and are using those credentials
console.log('Signed in as: ' + user.userName);
} else {
console.log('Not signed in.')
if (online)
{
alert('signing in');
authContext.login();
}
else
{
alert('currently offline');
}
}
}
Ok...I made the change and the error is gone but I don't understand how this is supposed to address the issue. When I add my page to my IPhone home screen (https://xxxxx.azurewebsites.net/app/test.html) and then click on the tile I am taken to the test.html page. On that page page there is an auth function that executes which uses adal.js and takes me to "https://login.microsoftonline.com/xxx.onmicrosoft.com/oauth2...". This shows up in the scope of my IOS Web app and has my account listed and the Use another account option. I click on my account or choose the Use another account option and I am taken to another page that is opened in Safari.

Categories

Resources