How do I make a script work in a specific browser?

Asked

Viewed 65 times

4

How do I make a script work only in a specific browser, for example: that works only in Chrome? And the opposite: block the script from working in a specific browser? What do I have to add to the code? I use HTML and the script in question is:

function openWindow() {          
  window.open("banner","Teste","width=731,height=420,top=100,left=250");
}

1 answer

4

You can use the property navigator, accessible through the global object window.

This property contains various information related to the user’s browser. For this answer, we will focus on the property userAgent, containing a string a little complicated and full of information. Among them, we can find the name of the browser in use. Something like this:

Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_1) Applewebkit/536 (KHTML, like Gecko) Chrome/72.0.3626.111 Safari/536.47


With the example below, you can detect which browser the user is using:

if (navigator.userAgent.includes('Chrome')) {
  alert('Você usa o Google Chrome')
} else if (navigator.userAgent.includes('Opera')) {
  alert('Você usa o Opera')
} else if (navigator.userAgent.includes('Firefox')) {
  alert('Você usa o Mozilla Firefox')
} else if (navigator.userAgent.includes('Safari')) {
  alert('Você usa o Safari')
} else if (navigator.userAgent.includes('MSIE')) {
  alert('Você ainda usa IE? Como consegue?!')
} else {
  alert('Você usa um navegador pouco comum...')
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.