JavaScript useful tips and examples | Drupal 8

JavaScript useful tips and examples

Submitted by editor on Tue, 01/23/2018 - 10:29
Question

How to get HTTP Header information on client side using java script ?
How to get query parameters from JS like $_GET on php ?
How to Check if Function, method or Class Exists ?

Get HTTP Header information From JavaScript

Note : It's not possible to read the current headers. You could make another request to the same URL and read its headers, but there is no guarantee that the headers are exactly equal to the current.

Example:
var req = new XMLHttpRequest();
req.open('GET', document.location, false);
req.send(null);
//var headers = req.getAllResponseHeaders().toLowerCase();
var headers = req.getAllResponseHeaders();
//
// Get a particular header (Hear : Cache-Control).
headers = headers.split("\r\n");
headers.forEach(function (entry) {
    if (entry.indexOf("Cache-Control") !== -1) {
        console.log(entry.split(":")[1].trim());
    }
});

Note : Most of common informations are available under 'navigator' which does not need a second request. try : console.log(navigator);

Get Query String Parameters with JavaScript

The RAW data is available from  window.location.search , This gives everything after the '?'.
Try console.log(window.location.search);

Get a particular parameter.
Example : (Hear "?post=1234&action=edit")
var urlParams = new URLSearchParams(window.location.search);
if (urlParams.has('post')) {
var postValue = urlParams.get('post');
}

And provide different functions :
var urlParams = new URLSearchParams(window.location.search);
console.log(urlParams.has('post')); // true
console.log(urlParams.get('action')); // "edit"
console.log(urlParams.getAll('action')); // ["edit"]
console.log(urlParams.toString()); // "?post=1234&action=edit"
console.log(urlParams.append('active', '1')); // "?post=1234&action=edit&active=1"

Note : URLSearchParams is not supported by old web browsers.
Check the compatibility : https://caniuse.com/#feat=urlsearchparams

You can also do like:
function getUrlParameter(name) {
    name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
    var regex = new RegExp('[\\?&]' + name + '=([^&#]*)');
    var results = regex.exec(location.search);
    return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, ' '));
};
getUrlParameter('post'); // "1234"
getUrlParameter('action'); // "edit"

 

Check if Function, method or Class Exists Before Calling

//Example 1:
if (typeof yourFunctionName == 'function') {
  yourFunctionName();
}
//
//Example 2:
if (typeof URLSearchParams == 'function') {
  var urlParams = new URLSearchParams(window.location.search);
}
//
//Example 3 : If function not exist
if (typeof URLSearchParamsError == 'undefined') {
  console.log("This class not available");
}

 

 

Add new comment