2

Is it cross-browser safe to use JavaScript to fetch server paths? For a Joomla template, I have a number of JavaScript files that will be included via SCRIPT tags; these files need server paths, such as the site root. Here's some JS code that I found which gets server paths:

var hash = self.location.hash //       Sets or retrieves the subsection of the href property that follows the number sign (#). 
var host = self.location.host   //    Sets or retrieves the hostname and port number of the location or URL. 
var hostname = self.location.hostname //  Sets or retrieves the host name part of the location or URL.  
var href = self.location.href     //  Sets or retrieves the entire URL as a string.  
var pathname = self.location.pathname //  Sets or retrieves the path and file name associated with a URL.    
var port = self.location.port     //  Sets or retrieves the port number associated with a URL. 
var protocol = self.location.protocol //  Sets or retrieves the protocol portion of a URL.  

alert('hash: ' + hash + '\n' + 
   'host: ' + host + '\n' + 
   'hostname: ' + hostname + '\n' + 
   'href: ' + href + '\n' + 
   'pathname: ' + pathname + '\n' + 
   'port: ' + port + '\n' + 
   'protocol: ' + protocol);

The above JavaScript returns this:

hash: #panel-1
host: localhost:8090
hostname: localhost
href: http://localhost:8090/joomla/#panel-1
pathname: /joomla/
port: 8090
protocol: http

The Joomla site will run across many browsers, platforms, and devices. Will the above JS code work well for these scenarios or is it better to use PHP to fetch server paths? Thanks.

2 Answers 2

3

Use PHP. You can't reliably retrieve the server paths using client-side scripting: e.g., using mod_rewrite in Apache one can change the way URLs relate to (local) server paths.

Sign up to request clarification or add additional context in comments.

1 Comment

Ahhh... didn't know that. That makes sense and so PHP is the more reliable way. Thanks.
0

Server side (PHP) works better because what if the client disables JavaScript. Of course without mentioning server rewrite and etc

1 Comment

In this case, the code will be used in SCRIPT files included via the SRC attribute. So the entire file would not be called if client scripting is disabled, and thus the point would be moot.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.