-
-
Save drbh/250a77a438624bc2619f0518dd5b38fe to your computer and use it in GitHub Desktop.
// 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() |
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?..
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
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
This is beautiful! You're my hero 😄