3

I have the following code which basically does the following:

When the user clicks the button, an encoded text is sent to an API which takes care to decode it. Then the decoded text is set as a query on a Google link which is opened on a new tab.

JAVASCRIPT

// Reference:
// https://base62.io/
let message_encoded = 'T8dgcjRGkZ3aysdN'; // base62('Hello World!'')
let way = 1;

$(function () {
  $('.button_test').click(async function() {
    let url_api = 'https://api.base62.io/decode';
    let response;
    switch (way) {
        case 1: /* this works */
            response = await jQuerySyncPost(url_api, { data: message_encoded });
            break;
        case 2: /* this DOES NOT work */
            response = await fetchSyncPost(url_api, { data: message_encoded });
            break;
        case 3: /* this DOES NOT work */
            response = await axios.post(url_api, { data: message_encoded });
            break;
    }
    alert('Next, let\'s look on Google for: "' + response.data.decoded + '"');
    let message_decoded = response.data.decoded;
    let url_google = 'https://www.google.com/search?q='+encodeURIComponent(message_decoded);
    openNewTab(url_google);
  });
});
function jQuerySyncPost(url, params) {
  return new Promise((resolve, reject) => {
    $.ajax({
      type: 'POST',
      url: url,
      data: params,
      async: false,
      success: function (response) {
        response = {
          data: response
        };
        resolve(response);
      },
      error: function (jqXHR, textStatus, errorThrown) {
        reject({
          jqXHR: jqXHR,
          textStatus: textStatus,
          errorThrown: errorThrown
        });
      }
    });
  });
}
function fetchSyncPost(url, params) {
  return new Promise((resolve, reject) => {
    let config = {
        headers: {
        'content-type': 'application/json; charset=UTF-8',
      },
      body: JSON.stringify(params),
      method: 'POST',
    };
    fetch(url, config)
      .then(response => response.json())
      .then(response => {
        let result = {
          data: response,
        };
        resolve(result);
      });
    });
}
function openNewTab(url) {
  window.open(url, '_blank');
}

HTML

<button class="button_test">Click Here</button>

CSS

.invisible {
  visibility: hidden;
}

.button_test {
  margin-left: 200px;
  margin-top: 100px;
  font-size: 50px;
}

The code above is working fine with the jQuery Ajax call (through custom function):

let response = await syncPost(url_api, { data: message_encoded });

But, in the other hand, if I use axios, then I get a popup blocked alert on the browser which prevents the new tab to get opened:

let response = await axios.post(url_api, { data: message_encoded });

Here you have the JSFiddle: https://jsfiddle.net/otyzadju
where { way=1 } works, but { way=2, way=3 } don't.

On both cases the call to the API via Ajax is done synchronously but the problem is that it seems that axios is disconnecting what happens next from user's action when called after clicking a button.

Any idea on how to make this work with axios?

If possible, please, provide your solution on a forked JSFiddle link.

Thanks!

Viewsonic
  • 827
  • 2
  • 15
  • 34
  • This is a bit similar - I hope it helps: https://stackoverflow.com/questions/4602964/how-do-i-prevent-google-chrome-from-blocking-my-popup – Sparlarva Nov 17 '18 at 08:55
  • @Sparlarva that's not similar. They don't use `axios`. My goal is to use `Axios`. – Viewsonic Nov 17 '18 at 15:45
  • Okay but you haven't posted a problem using an axios solution. – Sparlarva Nov 17 '18 at 18:17
  • yes I did, just uncomment the line: `await axios.post` and comment the line: `await syncPost` – Viewsonic Nov 17 '18 at 18:31
  • Have you looked in the development console to see what the error is on the browser? I can also see that there are no headers added when you are using axios? – Sparlarva Nov 17 '18 at 18:38
  • there is no error on the console log. I also tried with `window.fetch` API but it didn't work either. Please, check the `JSFiddle` example above with: `way=2`. Just in case, I copy paste the link here too: https://jsfiddle.net/73bufk4r – Viewsonic Nov 17 '18 at 18:54
  • I basically changed to window.open but i realise that your opennewtab function also includes some other attributes, please let me know if you need any. – Sparlarva Nov 17 '18 at 19:09
  • I updated the test code to: https://jsfiddle.net/otyzadju but keep getting the popup blocker with: `{ way=2, way=3 }`. – Viewsonic Nov 17 '18 at 19:26

1 Answers1

0

I changed the answer to window.open so it will work with axios.post - it also works with fetch. If you didn't use this originally for a certain reason then please let me know and I can try and update the answer.

function openNewTab(url) {
      window.open(url, '_blank')

}

This is a JSfiddle fork with it set to option 2 and the opennewtab function altered.

https://jsfiddle.net/xuywfqzn/

Sparlarva
  • 790
  • 1
  • 8
  • 30
  • Unfortunatelly I keep getting the popup blocker with: `{ way=2, way=3 }`. I ended up using the other code for `openNewTab(...)` I think because I tried wrong parameters with `window.open(...)` initially. I updated it's code, thanks for that. Beside that, I keep having the issue with the popup blocker. Do you say you don't get the popup blocker?, maybe you disabled it on the browser config? I tried with both: `Chrome` and `Firefox` and on both browsers I get the popup blocker with ways: 2 and 3. Here is my code updated: https://jsfiddle.net/otyzadju Thanks! – Viewsonic Nov 17 '18 at 19:25
  • My pop up definitely disappeared even with it enabled i checked but let me look again, give me a little time im just about to have my birthday cake (dont worry its my birthday in 4 days - just at my parents) – Sparlarva Nov 17 '18 at 20:43