I need to show different app link depends on user operation system.
Such as IOS, Android or both if user is opening page on Desktop.
I'm using React and Next.js
I tried to use navigator.userAgent with no luck.
It will be perfect to achieve code like below:
import React from "react";
import { AppDownload as AppDownloadProps } from "xxx";
export default function DownloadApp({
appDownload,
}: AppDownloadProps): JSX.Element {
return (
<div>
{isIos && <a href={appDownload?.ios.url}></a>}
{isAndroid && <a href={appDownload?.android.url}></a>}
{isDesktop && <a href={appDownload?.desktop.url}></a>}
</div>
);
}
Possible duplicate of Detect MacOS, iOS, Windows, Android and Linux OS with JS.
You can use window.navigator but will need to parse the result.
You can use navigator.userAgent to detect the useragent in browser and there are lots of other options are available to get agent information.
console.log("agent is:", window?.navigator?.userAgent)
console.log("platform is: ", window?.navigator?.platform)
console.log("user agent data: ", window?.navigator?.userAgentData)
Related
Looking to hide/show a component in a React/Nextjs/tailwind webapp depending on the device that the user is on (e.g. desktop vs tablet vs mobile) since there are certain keys on the keyboard available for desktop but not on table and mobile (e.g. the tab key). Don't want to do it by screen size since this is a device problem (no tab on keyboard) rather than a screen size problem
Initially I thought about getting device type (code referenced from another stackoverflow Q/A), but this seems to fail when the user is on a device such as an ipad and is using the Desktop version for that browser (e.g. Desktop safari and not mobile safari). Is there a better way to handle this such that it can properly check what device the user is on in order to be able to hide/show the react component?
const getDeviceType = () => {
const ua = navigator.userAgent;
if (/(tablet|ipad|playbook|silk)|(android(?!.*mobi))/i.test(ua)) {
return "tablet";
}
if (
/Mobile|iP(hone|od)|Android|BlackBerry|IEMobile|Kindle|Silk-Accelerated|(hpw|web)OS|Opera M(obi|ini)/.test(
ua
)
) {
return "mobile";
}
return "desktop";
};
In JavaScript you can detect browser with JavaScript using window.navigator
Code example according to https://developer.mozilla.org/en-US/docs/Web/API/Window/navigator would be
var sBrowser, sUsrAg =
navigator.userAgent;
// The order matters here, and this may
report false positives for unlisted
browsers.
if (sUsrAg.indexOf("Firefox") > -1) {
sBrowser = "Mozilla Firefox";
// "Mozilla/5.0 (X11; Ubuntu; Linux
x86_64; rv:61.0) Gecko/20100101
Firefox/61.0"
}
alert("You are using: " + sBrowser);
But for react there's another package you can use that is npm install react-device-detect
Code example would be
import { browserName, browserVersion }
from "react-device-detect"
console.log(`${browserName}
${browserVersion}`);
After detecting browser you just conditionally render whatever you want to show
developers,
I am working on a react native project that requires faceid login functionality.
Thanks to the libs and sample codes in the github repo, I implemented on my app very easily.
However, it displays the default bottom dialog when requiring the user to pass faceID auth in the android emulator.
react-native-biometrics
import ReactNativeBiometrics from 'react-native-biometrics';
//...
ReactNativeBiometrics.createSignature({
promptMessage: ' ',
payload: payload
})
.then((resultObject) => {
const { success, signature } = resultObject;
if (success) {
setMaskActive(true);
}
});
how can I remove the prompt dialog, but still keep calling ReactNativeBiometrics.createSignature() function?
Thank you.
I'm trying to get Web NFC to work through the Web NFC API, but I can't get it past an error message of NotAllowedError: NFC permission request denied.
I'm using this on Chrome 89 Dev on a Windows 10 computer, and the source code is being run locally.
I have tried the examples posted on the Internet also, including the Google sample but it returns the same error. I'm not concerned with it being experimental at this point as referring to this does show it has successfully passed the necessary tests, including permissions.
The HTML/JS code I'm using is below, and I've read the specification point 9.3, but I can't make sense of it to write it as code, so is there a guideline algorithm that would be helpful here to resolve this?
async function readTag() {
if ("NDEFReader" in window) {
const reader = new NDEFReader();
try {
await reader.scan();
reader.onreading = event => {
const decoder = new TextDecoder();
for (const record of event.message.records) {
consoleLog("Record type: " + record.recordType);
consoleLog("MIME type: " + record.mediaType);
consoleLog("=== data ===\n" + decoder.decode(record.data));
}
}
} catch(error) {
consoleLog(error);
}
} else {
consoleLog("Web NFC is not supported.");
}
}
async function writeTag() {
if ("NDEFWriter" in window) {
const writer = new NDEFWriter();
try {
await writer.write("helloworld");
consoleLog("NDEF message written!");
} catch(error) {
consoleLog(error);
}
} else {
consoleLog("Web NFC is not supported.");
}
}
function consoleLog(data) {
var logElement = document.getElementById('log');
logElement.innerHTML += data + '\n';
};
<!DOCTYPE html>
<html>
<head>
<script src="webnfc.js"></script>
</head>
<body>
<p>
<button onclick="readTag()">Test NFC Read</button>
<button onclick="writeTag()">Test NFC Write</button>
</p>
<pre id="log"></pre>
</body>
</html>
From https://web.dev/nfc/#security-and-permissions
Web NFC is only available to top-level frames and secure browsing contexts (HTTPS only). Origins must first request the "nfc" permission while handling a user gesture (e.g a button click). The NDEFReader scan() and write() methods trigger a user prompt, if access was not previously granted.
I guess you are running from a file:// URL as you said "locally" which is not supported.
You need to host it from a local web server using a https:// URL
Once in the right scope trying to scan or write should trigger a user prompt.
You can also check permissions see https://web.dev/nfc/#check-for-permission
Update:
So I tried the sample page https://googlechrome.github.io/samples/web-nfc/
And this works for me on Android Chrome 87 with "Experimental Web Platform features" enabled
When you hit the scan button A dialog asking for permission pops up.
Comparing the code in this sample to yours I notice that does:-
ndef.addEventListener("reading" , ({ message, serialNumber }) => { ...
Where as yours does:-
ndef.onreading = event => { ...
I don't know if it is the style setting what happens on the Event or something else (Hey this is all experimental)
Update2
To answer the question from the comments of Desktop support.
So you should be some of the desktop/browser combinations at the moment and may be in the future there will be wider support as this is no longer experimental standards. Obviously as your test link suggest Chrome on a Linux Desktop should work as this is really similar to Android Support, with all the NFC device handling done by libnfc and the browser just has to know about this library instead of every type usb or other device than can do NFC.
From what seen of NFC support on Windows, most of this is focussed on direct controlling the NFC reader via USB as just another USB device, while there is a libnfc equivalent in Windows.Networking.Proximity API's I've not come across any NFC reader saying they support this or anybody using it.
For Mac Deskstop, given that Apple are behind the curve with NFC support in iOS, I feel their desktop support will be even further behind even though it could be similar to Linux.
As you can read at https://web.dev/nfc/#browser-support, Web NFC only supports Android for now which is why you get "NotAllowedError: NFC permission request denied." error on Windows.
I have a scenario where i need to enter email and click on submit button but when webdriver enters email and clicks on submit button an error is thrown "Email is Required" although webdriver entered the email which i can see. I have this issue on Firefox and Safari both on Desktop and mobile devices. With a bit of research i able to fix for Firefox with below javascript code.
JavascriptExecutor js = ((JavascriptExecutor)driver);
js.executeScript("var e=document.getElementById('email'); e.dispatchEvent(new Event('change')); e.dispatchEvent(new Event('blur')); return true;" );
But the same code does not work on mobile safari on real device. Could someone help in fixing this issue ?
Environment
Appium version - 1.6.5 Mac os : 10.12.6 Node.js version - 3.10.10
Mobile platform/version under test: - 10.3 Iphone 6 Real device Using
Appium desktop client Logs: <script
src="https://gist.github.com/mahesh-thuma/f02f6fdc81d48d4c0a16e2dd71412e0c.js"></script>
Figured out the issue. There is a small change in the email attribute from desktop ("email") to mobile ("Email"). Modified the javascript accordingly and i am able to proceed ahead. Though this is still an workaround but does the job. Closing this issue and Thanks to anyone investing time on this.
import Page from './page';
class YahooPage extends Page {
/**
* define elements
*/
get searchInput() { return browser.element('#yschsp'); }
get searchButton() { return browser.element('//div[#class="mag-glass"]'); }
get resultsList() { return browser.element('#results'); }
/**
* define or overwrite page methods
*/
open () {
super.open('https://search.yahoo.com') //provide your additional URL if any. this will append to the baseUrl to form complete URL
browser.pause(1000);
}
enterText (item) {
this.searchInput.clearElement();
this.searchInput.setValue(item);
}
search () {
this.searchButton.click();
}
isSearched () {
this.resultsList.waitForVisible(1000);
return this.resultsList.isVisible();
}
}
export default new YahooPage();enter code here
I'm using the HTML5 notification API to notify the user in Chrome or Firefox. On desktop browsers, it works. However in Chrome 42 for Android, the permission is requested but the notification itself is not displayed.
The request code, works on all devices:
if ('Notification' in window) {
Notification.requestPermission();
}
The sending code, works on desktop browser but not on mobile:
if ('Notification' in window) {
new Notification('Notify you');
}
Try the following:
navigator.serviceWorker.register('sw.js');
Notification.requestPermission(function(result) {
if (result === 'granted') {
navigator.serviceWorker.ready.then(function(registration) {
registration.showNotification('Notification with ServiceWorker');
});
}
});
That is, use ServiceWorkerRegistration»showNotification() not new Notification().
That should work on Android both in Chrome and in Firefox — and on iOS in Safari, too.
(The sw.js file can just be a zero-byte file.)
One caveat is that you must run it from a secure origin (an https URL, not an http URL).
See https://developer.mozilla.org/docs/Web/API/ServiceWorkerRegistration/showNotification.
If you already have a service worker registered, use this:
navigator.serviceWorker.getRegistrations().then(function(registrations) {
registrations[0].showNotification(title, options);
});
Running this code:
if ('Notification' in window) {
Notification.requestPermission();
}
Console in Chrome DevTools shows this error:
Uncaught TypeError: Failed to construct ‘Notification’: Illegal
constructor. Use ServiceWorkerRegistration.showNotification() instead
A better approach might be:
function isNewNotificationSupported() {
if (!window.Notification || !Notification.requestPermission)
return false;
if (Notification.permission == 'granted')
throw new Error('You must only call this \*before\* calling
Notification.requestPermission(), otherwise this feature detect would bug the
user with an actual notification!');
try {
new Notification('');
} catch (e) {
if (e.name == 'TypeError')
return false;
}
return true;
}
Function Source: HTML5Rocks
I had no trouble with the Notification API on Windows Desktop. It even worked without issues on Mobile FF. I found documentation that seemed to indicate Chrome for Android was supported too, but it didn't work for me. I really wanted to prove the API could work for me on my current (2019) version of Chrome (70) for Android. After much investigation, I can easily see why many people have had mixed results. The answer above simply didn't work for me when I pasted it into a barebones page, but I discovered why. According to the Chrome debugger, the Notification API is only allowed in response to a user gesture. That means that you can't simply invoke the notification when the document loads. Rather, you have to invoke the code in response to user interactivity like a click.
So, here is a barebones and complete solution proving that you can get notifications to work on current (2019) Chrome for Android (Note: I used jQuery simply for brevity):
<html>
<head>
<script type="text/javascript" src="libs/jquery/jquery-1.12.4.min.js"></script>
<script>
$( function()
{
navigator.serviceWorker.register('sw.js');
$( "#mynotify" ).click( function()
{
Notification.requestPermission().then( function( permission )
{
if ( permission != "granted" )
{
alert( "Notification failed!" );
return;
}
navigator.serviceWorker.ready.then( function( registration )
{
registration.showNotification( "Hello world", { body:"Here is the body!" } );
} );
} );
} );
} );
</script>
</head>
<body>
<input id="mynotify" type="button" value="Trigger Notification" />
</body>
</html>
In summary, the important things to know about notifications on current (2019) Chrome for Android:
Must be using HTTPS
Must use Notification API in response to user interactivity
Must use Notification API to request permission for notifications
Must use ServiceWorker API to trigger the actual notification
new Notification('your arguments'); This way of creating notification is only supported on desktop browsers, not on mobile browsers. According to the link below. (scroll down to the compatibility part)
https://developer.mozilla.org/en-US/docs/Web/API/Notifications_API/Using_the_Notifications_API
For mobile browsers below is the way you create a notification (this also works on desktop browsers)
navigator.serviceWorker.ready.then( reg => { reg.showNotification("your arguments goes here")});
Tested on browsers using webkit engine.
For more information please visit below links:
https://developers.google.com/web/updates/2015/05/notifying-you-of-changes-to-notifications
https://developers.google.com/web/fundamentals/push-notifications/display-a-notification