Animesh
Animesh

Reputation: 427

Javascript function not defined when call from browser console

var ready = function ready(callback) {
      if (document.readyState != "loading") callback();else document.addEventListener("DOMContentLoaded", callback);
    };
    ready(function () {
      "use strict"; 
      var callBstApi = function callBstApi(params) {
        fetch("http://localhost:3000/api/v1/myApi", {
          method: 'POST',
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify(params)
        }).then(function (data) {
          console.log(JSON.stringify(params));
        }).catch(function (error) {
          console.log('test is cancelled!');
        });
      };
    });
    

When I call callBstApi(myParams) onload it works but if I call that function from my browser console it shows below error Error!!!

I have to write script in vanilla js.

Upvotes: 0

Views: 573

Answers (1)

Terry
Terry

Reputation: 66103

To further extend on my comment: the reason why callBstApi is not available in your console is because it is not present in the global scope. The function is defined inside your ready function and is therefore inaccessible. To circumvent this, you will want to expose the method to the global window scope. This can be done by doing so:

window.callBstApi = ...

You can now access callBstApi in the global scope (with or without the window. prefix, that is completely optional) and invoke it as such:

callBstApi(myParams);

// If you want to be pedantic, you can do:
window.callBstApi(myParams);

p/s: The only risk is that you'll overwrite whatever that's there, if that key is already found in the window object.

Upvotes: 1

Related Questions