24 Feb Javascript: Creates an useful and global function that can be used wherever you want to get the current domain url(protocol, domain, port)
After thinking a little bit I don’t remember writing too much about javascript and I really like javascript !!!, well here it is the first post that I want you to share with you guys.
Sometimes you need to get the absolute url from javascript for those cases you can find useful the following function:
window.Utils = { httpUrlFor: function(url_params) { var domain, port; domain = "http://" + window.location.hostname; port = window.location.port ? ":" + window.location.port : ""; return domain + port + url_params; } }; # or in coffee-script window.Utils = httpUrlFor: (url_params) -> domain = "http://#{window.location.hostname}" port = if window.location.port then ":#{window.location.port}" else "" "#{domain}#{port}#{url_params}"
And after that you require this javascript function in your html or your application javascript file all you need to do is invoke it:
Utils.httpUrlFor('/events/index') # the above code will produce something like # http://localhost:3000/events/index # or # https://blog.elh.mx/events/index # depending where you are invoken the function of course
Or if you are using https too, you can use the following function with a little modification:
window.Utils = { httpUrlFor: function(url_params) { var domain, port; domain = window.location.protocol + "//" + window.location.hostname; port = window.location.port ? ":" + window.location.port : ""; return domain + port + url_params; } }; # or coffee window.Utils = httpUrlFor: (url_params) -> domain = "#{window.location.protocol}//#{window.location.hostname}" port = if window.location.port then ":#{window.location.port}" else "" "#{domain}#{port}#{url_params}"
that’s it you can use the function wherever you want because you are declaring it as a global function available in all the website.
Regards
H.
No Comments