raisingraisins
raisingraisins

Reputation: 21

Performing javascript action before every http request

Is it possible to perform an action before every http request sent upon clicking an a-href tag? I would like to perform the action before every referred http request as well (eg requests for images/scripts in the DOM). Thanks!

Upvotes: 1

Views: 2515

Answers (1)

Vignesh Raja
Vignesh Raja

Reputation: 8761

It can be achieved for every HTTP ajax request.

Note : Dummy requests in examples are made to HTTP Bin.

JAVASCRIPT:

References : JS XMLHttpRequest

(function init()
{
    XMLHttpRequest.prototype._open = XMLHttpRequest.prototype.open;
    XMLHttpRequest.prototype.open = function(method, url, async, user, password){
        initialChanges();
        this._open(method, url, async, user, password);
    };
})();

function initialChanges()
{
    alert("Making a Javascript ajax request.");
}

function makeRequestViaXHR()
{
    var req = new XMLHttpRequest();
    req.open("GET","https://httpbin.org/get",false,null,null);
    req.onreadystatechange=function(){
        if(req.readyState === 4)
        {
            if(req.status === 200)
            {
                console.log(req.responseText);
            }
            else
            {
                console.log("Request Failed");
            }
        }
    };
    req.send();
}
<button onclick="makeRequestViaXHR()">Make a dummy ajax request via Javascript</button>

JQUERY:

References : jQuery ajax, jQuery .ajaxSend

(function init()
{
    $(document).ajaxSend(function(event,xhr,settings){
        alert("Making a jQuery ajax request.");
    });
})();

function makeRequestViaJquery()
{
    $.ajax({
        url:"https://httpbin.org/get",
        method:"GET",
        async:true,
        success:function(response){
            console.log(response);
        },
        error:function(error){
            console.log(error);
        }
    });
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<button onclick="makeRequestViaJquery()">Make a dummy ajax request via jQuery</button>

In case of navigating to other pages, downloading files or mail addresses via <a> tag, execute the method on click using addEventListener.

References : HTML Element Subinterfaces

document.addEventListener("click", function(event){
    var elem = event.target;
    if(elem instanceof HTMLAnchorElement) //For <a> tag
    {
        executeThis();
    }
});

function executeThis()
{
    alert("Element is clicked");
}
<a href="https://httpbin.org/get">Click this anchor element</a>
<a href="https://dummyimage.com/300" download="image.png">Download Image</a>

Scripts execute only after the DOM is loaded. If some function need to be executed before loading the images, you need to add the method with a script tag before every img element. Refer this for more info.

Upvotes: 1

Related Questions