简体   繁体   中英

How to catch a 403 forbidden error in JS?

I am trying to hack a little this facebook javascript code to make a call on an other js if the GET failed.

I have something like this :

<div id="fb-root"></div>
<script>(function(d, s, id) {
  var js, fjs = d.getElementsByTagName(s)[0];
  if (d.getElementById(id)) return;
  js = d.createElement(s); js.id = id;
  js.src = "//connect.facebook.net/yi_YI/all.js#xfbml=1&appId=###";
  fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));</script>
<div class="fb-comments" data-href="###" data-num-posts="10" data-width="646"></div>

Which give a 403 Forbidden ( /* Not a valid locale. */ ). When it does something like this, I want to be able to load the en_US facebook sdk. So, I have tried :

<div id="fb-root"></div>
<script>(function(d, s, id) {
  var js, fjs = d.getElementsByTagName(s)[0];
  if (d.getElementById(id)) return;
  js = d.createElement(s); js.id = id;
  js.src = "//connect.facebook.net/yi_YI/all.js#xfbml=1&appId=###";
  try { fjs.parentNode.insertBefore(js, fjs); }
  catch(err) {
      js.src = "//connect.facebook.net/en_US/all.js#xfbml=1&appId=###";
      fjs.parentNode.insertBefore(js, fjs);
  }
}(document, 'script', 'facebook-jssdk'));</script>
<div class="fb-comments" data-href="###" data-num-posts="10" data-width="646"></div>

But, it doesn't work, keep getting 403 Forbidden, like if the try and catch(err) is not working.

You can't get the HTTP response status of a cross-domain request.

The reason you're getting a 403 is because Facebook doesn't support yi_YI as a locale – you will always get a 403. The locale you request must be on the list of supported locales .

use onerror method for script:

<div id="fb-root"></div>
<script>(function(d, s, id) {
  var js, fjs = d.getElementsByTagName(s)[0];
  if (d.getElementById(id)) return;
  js = d.createElement(s); js.id = id;
  js.src = "//connect.facebook.net/yi_YI/all.js#xfbml=1&appId=###";

  //handle loading error 
  js.onerror = function(){alert("script loading error")};

  fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));</script>
<div class="fb-comments" data-href="###" data-num-posts="10" data-width="646"></div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM