Chrome, allow autoconnect for HID device - javascript

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.

Related

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

Detect removal of restriction of devices

Using getUserMedia to let user select microphone. Further I use enumerateDevices to create a select with devices so that user can change device from UI.
I am on Firefox and have not checked how others browsers fare, but at least for FF I have not found a solution.
If user selects to not allow access when asked one do not get to ask again[ 1 ] until user removes the restriction:
Question is if there is a way to detect when user removes the restriction?
Scenario is typically:
User loads page and are asked to select input device
User rejects
UI disables device selector + hide various stuff
User removes restriction (as per picture above)
UI enables device selector + unhide various stuff
There is (obviously) not a way to reset the block from client side by Java Script, but is there a way to detect that user revokes the block? (Or is there? Sounds like something that could be exploited to keep looping a request for access.)
One could do a loop where one keep trying for the lifetime of the page, but would like to avoid that. Looking for an event for this.
In that regard, ondevicechange, does not trigger an event when block is removed - which is logical in a way as there is not a change in the available devices, in a way :P.
[ 1 ] That is: one can ask, but it result in a:
MediaStreamError
message: The request is not allowed by the user agent or the platform in the current context.
name: NotAllowedError
​
You should be able to detect this change from the Permissions API.
The PermissionStatus object returned by Permissions.prototype.query() has an onchange event handler. So a query to the "camera" or "microphone" will fire its change event when the user changes their setting.
const camera_perm = await navigator.permissions.query( { name: 'camera' } );
camera_perm.onchange = (evt) => {
const allowed = camera_perm.state === "granted";
if( allowed ) {
// ...
}
else {
}
};
This currently works in Chrome, but Firefox still doesn't support neither the "camera" nor the "microphone" members of PermissionDescriptor.
So for that browser, the closest we can have is through polling, as explained in this Q/A: Event listener that "camera and microphone blocked" is allowed .

Web Share API permission missing

I'm trying to implement the Web Share Api functionality on my test web app but it doesn't seem I'm able to do it. This is the code:
const newVariable: any = navigator;
{newVariable && newVariable.share && <IconButton aria-label="Share" onClick={async (e) => {
try {
const id = await shareRepository.shareTrip(this.props.todolist)
const url = "https://something.com/share/" + id
await newVariable.share({
title: 'Check my todolist for ' + this.props.todolist.trip.departure + ' - ' + this.props.todolist.trip.arrival,
text: 'Check my todolist for ' + this.props.todolist.trip.departure + ' - ' + this.props.todolist.trip.arrival,
url: url,
})
} catch (error) {
alert(error)
}
}}>
<ShareIcon />
</IconButton>}
Every time I try on both Firefox and Safari for iOS, I'm getting an error saying:
NotAllowedError: the request is not allowed by the user agent or the platform in the current context, possibly because the user denied permission.
If on those browser I try to share something from google.com I get the native dialog to choose with which app to share.
I cannot understand why. On this page there is no discussion about permission: https://developers.google.com/web/updates/2016/09/navigator-share
UPDATE:
on Chrome for android works just fine, on Firefox for Android doesn't work. On Chrome, Firefox and Safari (which I believe they use safari engine all three) is only working if I pass "" which means the page itself, or "https://something.com/share/", it breaks If I pass "https://something.com/share/"+id :/
For other future users where the current answer is too specific to that code. The root issue is that the share() method must be called from a user gesture.
If the method call was not triggered by user activation, return a promise rejected with with a "NotAllowedError" DOMException.
From the Web Share API.
A user activation is any of the following:
change
click
contextmenu
dblclick
mouseup
pointerup
reset
submit
touchend
I understood what was the issue, which is absolutely annoying.
So:
const id = await shareRepository.shareTrip(this.props.todolist)
This call is the one that is causing problems. If I comment it, on iOS there is no issue.
If I keep it I have no problem at all on Android but iOS will complain.
So I need to rethink the flow of the application to pass the id from outside the 'onClick' event.

Why doesn't callback get called when the app is in background?

I'm developing a titanium app that needs to display a Banner Message under iOS when a push notification comes in. Therefore I used the following code to register on incoming push notifications:
var callbacks = {
types: [
Titanium.Network.NOTIFICATION_TYPE_BADGE,
Titanium.Network.NOTIFICATION_TYPE_SOUND,
Titanium.Network.NOTIFICATION_TYPE_ALERT
],
success:function(e){
console.log("success");
},
error:function(e){
console.log("error");
},
callback: function(e){
console.log("new push notification")
//code for displaying banner message would go here!
}
};
if(Ti.App.iOS.registerUserNotificationSettings){ //iOS 8 +
function onUserNotificationSettings(){
delete callbacks.types;
Ti.Network.registerForPushNotifications(callbacks);
Ti.App.iOS.removeEventListener("usernotificationsettings",onUserNotificationSettings);
}
Ti.App.iOS.addEventListener("usernotificationsettings",onUserNotificationSettings)
Ti.App.iOS.registerUserNotificationSettings(callbacks)
}else{ //up to iOS 7
Ti.Network.registerForPushNotifications(callbacks)
}
But the callback function does not get called when the app is in background. So, I also can't display the banner message there, since the code won't get executed.
What could be the reason why the callback does not get called when the app is in background? When it is in foreground, it works perfectly. Is it normal? If yes, where else would I put my code to display the banner message?
I'm using SDK version 3.4.0 on an iPhone 5 with iOS 8.1.1
Please note that sending the banner text through the apn-payload is not the solution. There are other usecases. For example, when the server needs to tell the client that there is new content to sync, where the user does not even need to get notified for. The client should just download the new content in background just when the notification arrives.
You need to register for the remote-notification background mode. This will wake up your app and give you execution time when you send the notifications.
For the record this is in the Appcelerator docs here
I've found out how to do it!
The callback will get called when the app is in background. All I had to do for it was to add the following to my tiapp.xml in ti:app/ios/plist/dict:
<key>UIBackgroundModes</key>
<array>
<string>remote-notification</string>
</array>
After that, everything works fine!

How to detect Chrome extension uninstall

I am trying to detect whether my extension was uninstalled.
I can't use chrome.management.onUninstalled because it will be fired on other extension.
As of Chrome 41, you can now open a URL when the extension is uninstalled. That could contain an exit survey or track the uninstall event as some sort of analytics.
Google Chrome, unlike Firefox, doesn’t allow to detect when the user uninstalls the extension, which is quite useful to understand user behaviour.
There is a feature request on crbug.com with a discussion of this feature but it has not been implemented yet.
You can call chrome.runtime.setUninstallURL("www.example.com/survey") and redirect user to a url. Unfortunately, as soon as the extension is removed, the background script is removed too, and you can't do anything like log event or send hit to google analytics.
What I did is to set the redirect url to my server endpoint, and do some tasks like logging event to my own db, or sending hit to google analytics (ga hit builder). Then call res.status(301).redirect("www.example.com/survey") to some survey url. Finally I can send the uninstall event to google analysis.
If you're on Manifest V3, you can add it on your onInstalled Listener. If you want to capture uninstall for existing users as well, you need to add it to 'update' as well.
Place this code in your background page:
chrome.runtime.onInstalled.addListener(function (details) {
if (details.reason == 'install') {
... can add things like sending a user to a tutorial page on your website
chrome.runtime.setUninstallURL('https://www.yourwebsite.com/uninstall');
} else if (details.reason == 'update') {
... can add things like sending user to a update page on your website
chrome.runtime.setUninstallURL('https://www.yourwebsite.com/uninstall');
}
});
Find more information here: https://developer.chrome.com/docs/extensions/reference/runtime/#method-setUninstallURL
For mv3: An easy way would be to have
// Redirect users to a form when the extension is uninstalled.
const uninstallListener = (details) => {
if (details.reason === chrome.runtime.OnInstalledReason.INSTALL) {
chrome.runtime.setUninstallURL('https://forms.gle/...');
}
if (details.reason === chrome.runtime.OnInstalledReason.UPDATE) {
// TODO: show changelog
}
};
chrome.runtime.onInstalled.addListener(uninstallListener);
Place it in your background.
Content Script can Detect an Uninstall
Simply check the value of chrome.runtime, which becomes undefined when an extension is uninstalled.
A good trigger to check this is port disconnect:
// content_script.js
const port = chrome.runtime.connect();
port.onDisconnect.addListener(onPortDisconnect);
function onPortDisconnect() {
// After the extension is disabled/uninstalled, `chrome.runtime` may take
// a few milliseconds to get cleared, so use a delay before checking.
setTimeout(() => {
if (!chrome.runtime?.id) {
console.log('Extension disabled!');
}
}, 1000);
};

Categories

Resources