Skip to content

Instantly share code, notes, and snippets.

@ZachMoreno
Created July 8, 2019 01:45
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ZachMoreno/5c2f7f189e4bc3d3ba907b3d20bdeb84 to your computer and use it in GitHub Desktop.
Save ZachMoreno/5c2f7f189e4bc3d3ba907b3d20bdeb84 to your computer and use it in GitHub Desktop.
The Brave Browser removed "Brave" from its User-Agent in v0.9. DuckDuckGo can detect Brave & this promise utilizes their API to detect Brave.
const detectBraveBrowser = () => {
return new Promise((resolve, reject) => {
if(!navigator.userAgent.includes('Chrome')) { return resolve(false); }
const xhr = new XMLHttpRequest();
const onload = () => {
if(xhr.status >= 200 && xhr.status < 300) {
const response = JSON.parse(xhr.responseText);
if(!response) { return resolve(false); }
if(!response.Answer) { return resolve(false); }
if(!response.Answer.includes('Brave')) { return resolve(false); }
return resolve(true);
} else {
return reject(JSON.parse(xhr.responseText));
}
};
xhr.onload = onload;
xhr.open('GET', 'https://api.duckduckgo.com/?q=useragent&format=json');
xhr.send();
});
};
detectBraveBrowser().then((isBrave) => {
console.log('isBrave', isBrave);
}).catch((error) => { console.error(error); });
@ZachMoreno
Copy link
Author

@miguelmota
Copy link

One-liner

const isBrave = (await (await fetch('https://api.duckduckgo.com/?q=useragent&format=json')).json()).Answer.includes('Brave')
console.log(isBrave) 

@FatBirdie
Copy link

One-liner

const isBrave = (await (await fetch('https://api.duckduckgo.com/?q=useragent&format=json')).json()).Answer.includes('Brave')
console.log(isBrave) 

Script works fine on desktop, but not on mobile.

@lschatzkin
Copy link

When I try to use the one-liner above, I get a syntax error that there's a ) missing, but I don't see it. Is anyone else having this problem?

When I use the Detect_Brave_Browser.js code, I can't seem to use the isBrave variable outside the function, no matter how I declare it. What's the best way to make that variable global?

Thanks!

@vascYT
Copy link

vascYT commented Mar 8, 2021

I had the same problem. You just have to put everything in an async function, then it should work.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment