Skip to content

Instantly share code, notes, and snippets.

@drbh
Created January 30, 2019 20:19
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save drbh/250a77a438624bc2619f0518dd5b38fe to your computer and use it in GitHub Desktop.
Save drbh/250a77a438624bc2619f0518dd5b38fe to your computer and use it in GitHub Desktop.
Reliably detect Brave Browser with native JS
// helper to find Brave in User Agent string
function isBraveAgent(userAgentResponse) {
var isBraveIndex = ~userAgentResponse.indexOf('Brave')
if (isBraveIndex < 0) {
return true
}
return false
}
// Function from Javarome
// https://stackoverflow.com/questions/3760319/how-to-force-a-program-to-wait-until-an-http-request-is-finished-in-javascript
function httpRequest(address, reqType, asyncProc) {
var req = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
if (asyncProc) {
req.onreadystatechange = function() {
if (this.readyState == 4) {
asyncProc(this);
}
};
}
req.open(reqType, address, !(!asyncProc));
req.send();
return req;
}
// Check reflected User Agent from whitelisted website (duckduckgo.com)
function checkIsBrave() {
var isBraveBrower = false
var req = httpRequest("https://api.duckduckgo.com/?q=whats+my+user+agent&format=json&pretty=1", "GET");
var duckDuckResponse = JSON.parse(req.responseText)
var userAgentResponse = duckDuckResponse["Answer"]
var foundBraveInUserAgent = isBraveAgent(userAgentResponse)
if (foundBraveInUserAgent){
isBraveBrower = true
}
return isBraveBrower
}
checkIsBrave()
@danielcolinjames
Copy link

This is beautiful! You're my hero 😄

@Dmitry-Klymenko
Copy link

So, why not just use navigator.brave?
Effectively the code below

if (typeof navigator.brave !== 'undefined')

saves the troubles of making an additional request and removes dependency on duckduckgo api?..

@danielcolinjames
Copy link

I haven't looked at this recently, but I believe the reason is because Brave doesn't identify itself as Brave in the name of protecting its users' privacy

@Dmitry-Klymenko
Copy link

Brave browser exposes property navigator.brave to DOM. So rather than making an HTTP request hoping for magic I could just do if (navigator.brave) {/* woohoo brave nrowser*/}

@danielcolinjames
Copy link

It appears they added that recently. It didn't used to be that easy (hence this gist)

@LucasArruda
Copy link

Interesting.

Here is the version that was implemented to test if navigator.brave implementation works (from Brave folks). Full discussion here: brave/brave-browser#8216

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