Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect safari and stop script

I have a script which I need to deactivate for safari (desktop only) due to compatibility issues.

The script must be in the body and cant be in a linked .js file.

I have tried to add a if statement in order to amend "Cburl" of the script so if safari is detected and a bad url is given so the script will not load.

Original

<script type="text/javascript">
    var cbuser = { name: '', email: '', message: '' },
        access_token = '3354777755',
        cburl = '//www.domain.com/help/';
        document.write('<script type="text/javascript" src="' + cburl + 'assets/help/js/script.js"></' + 'script>');
</script>

With safari detection:

    <script type="text/javascript">
    var safari = /^((?!chrome|android).)*safari/i.test(navigator.userAgent); //check if safari
    var cbuser = { name: '', email: '', message: '' },
        access_token = '3354777755',
    if(!safari){         
        cburl = '//www.domain.com/nohelp/';
        document.write('<script type="text/javascript" src="' + cburl + 'assets/help/js/script.js"></' + 'script>');
    }
    else {
    cburl = '//www.domain.com/help/';
    document.write('<script type="text/javascript" src="' + cburl + 'assets/help/js/script.js"></' + 'script>');
    }
</script>

Is there a fault with the way im detecting safari?

like image 736
thank_K Avatar asked Dec 17 '22 23:12

thank_K


1 Answers

I used to check if the user is using safari with this.

var isSafari = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);

Then you can stop the script doing this:

if(isSafari){ 
  alert('Is safari');
  //Do something

} else {
  alert('Is other browser');
  // Do something
}

Here is a fiddle so you can play with it.

Here is a snippet for your specific case. I changed the document.write to windows.location in order to make it work.

var isSafari = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);

if(isSafari) { 
   var cbuser = { name: '', email: '', message: '' };
   var access_token = '7654345676';
   window.location = "https://www.example.com/notSafari";
} else {
  var cbuser = { name: '', email: '', message: '' };
  var access_token = 'Z2SxfM5dRzKsm3Auhbi4';
  window.location = 'https://www.example.com';
} 

Just change the ´https://www.example.com´ to your URLs.

like image 53
goediaz Avatar answered Dec 28 '22 22:12

goediaz