geolocation.js 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. /*global wc_geolocation_params */
  2. jQuery( function( $ ) {
  3. var this_page = window.location.toString();
  4. var $append_hashes = function() {
  5. if ( wc_geolocation_params.hash ) {
  6. $( 'a[href^="' + wc_geolocation_params.home_url + '"]:not(a[href*="v="]), a[href^="/"]:not(a[href*="v="])' ).each( function() {
  7. var $this = $( this ),
  8. href = $this.attr( 'href' ),
  9. href_parts = href.split( '#' );
  10. href = href_parts[0];
  11. if ( href.indexOf( '?' ) > 0 ) {
  12. href = href + '&v=' + wc_geolocation_params.hash;
  13. } else {
  14. href = href + '?v=' + wc_geolocation_params.hash;
  15. }
  16. if ( typeof href_parts[1] !== 'undefined' && href_parts[1] !== null ) {
  17. href = href + '#' + href_parts[1];
  18. }
  19. $this.attr( 'href', href );
  20. });
  21. }
  22. };
  23. var $geolocation_redirect = function( hash ) {
  24. if ( this_page.indexOf( '?v=' ) > 0 || this_page.indexOf( '&v=' ) > 0 ) {
  25. this_page = this_page.replace( /v=[^&]+/, 'v=' + hash );
  26. } else if ( this_page.indexOf( '?' ) > 0 ) {
  27. this_page = this_page + '&v=' + hash;
  28. } else {
  29. this_page = this_page + '?v=' + hash;
  30. }
  31. window.location = this_page;
  32. };
  33. var $geolocate_customer = {
  34. url: wc_geolocation_params.wc_ajax_url.toString().replace( '%%endpoint%%', 'get_customer_location' ),
  35. type: 'GET',
  36. success: function( response ) {
  37. if ( response.success && response.data.hash && response.data.hash !== wc_geolocation_params.hash ) {
  38. $geolocation_redirect( response.data.hash );
  39. }
  40. }
  41. };
  42. if ( '1' === wc_geolocation_params.is_available ) {
  43. $.ajax( $geolocate_customer );
  44. // Support form elements
  45. $( 'form' ).each( function() {
  46. var $this = $( this );
  47. var method = $this.attr( 'method' );
  48. if ( method && 'get' === method.toLowerCase() ) {
  49. $this.append( '<input type="hidden" name="v" value="' + wc_geolocation_params.hash + '" />' );
  50. } else {
  51. var href = $this.attr( 'action' );
  52. if ( href ) {
  53. if ( href.indexOf( '?' ) > 0 ) {
  54. $this.attr( 'action', href + '&v=' + wc_geolocation_params.hash );
  55. } else {
  56. $this.attr( 'action', href + '?v=' + wc_geolocation_params.hash );
  57. }
  58. }
  59. }
  60. });
  61. // Append hashes on load
  62. $append_hashes();
  63. }
  64. $( document.body ).on( 'added_to_cart', function() {
  65. $append_hashes();
  66. });
  67. });