Created
January 30, 2019 20:19
-
-
Save drbh/250a77a438624bc2619f0518dd5b38fe to your computer and use it in GitHub Desktop.
Reliably detect Brave Browser with native JS
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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() |
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*/}
It appears they added that recently. It didn't used to be that easy (hence this gist)
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
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