Detect If Visitor Is on Index Page with Client Side Scripting

Detect if visitor is on index page with client side scripting

var homeUrl = 'http://www.example.com';
if ( document.URL == homeUrl ){
// true
}else{
// false
}

Now put an id on your image tag in the HTML:

<img src="/img/logo-home.png" id="logotype" />

Now you can easily find the image tag with javascript and change the source of the image depending on where you are on the site.

$(document).ready(function(){

var homeUrl = 'http://www.example.com';
var logotypeHome = '/img/logo-home.png';
var logotypeGeneral = '/img/logo-general.png';

if ( document.URL == homeUrl ){
$('#logotype').attr("src", logotypeHome);
}else{
$('#logotype').attr("src", logotypeGeneral);
}

});

I would still strongly recommend to go for a server-side solution for a thing like this. If the client doesn't have JavaScript enabled this will not work. Also there could be a flash on the image when the javascript changes the logo source.

Best way for checking if a user is logged with node.js and express and change client-side html

You may try something like this:

function checkIfLogged(callback){
$.get( '/checkIfLogged' , function(data) {
alert('Result checkIfLogged: '+data);
callback(data);
});
}

and

script.
checkIfLogged(function(authenticated) {
if(authenticated)

//I wouldn't use document.write here as it's a bit dangerous with asynchronous call

document.write("<div id='profile' class='myClass' ><p>SHOW PROFILE<p></div>");
else
document.write("<div id='register' class='myClass' ><p>REGISTER<p>");
});

How to detect a mobile device using jQuery

Editor's note: user agent detection is not a recommended technique for modern web apps. See the comments below this answer for confirmation of this fact. It is suggested to use one of the other answers using feature detection and/or media queries.


Instead of using jQuery you can use simple JavaScript to detect it:

if( /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ) {
// some code..
}

Or you can combine them both to make it more accessible through jQuery...

$.browser.device = (/android|webos|iphone|ipad|ipod|blackberry|iemobile|opera mini/i.test(navigator.userAgent.toLowerCase()));

Now $.browser will return "device" for all above devices

Note: $.browser removed on jQuery v1.9.1. But you can use this by using jQuery migration plugin Code


A more thorough version:

var isMobile = false; //initiate as false
// device detection
if(/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|ipad|iris|kindle|Android|Silk|lge |maemo|midp|mmp|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i.test(navigator.userAgent)
|| /1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(navigator.userAgent.substr(0,4))) {
isMobile = true;
}

check if javascript is available and redirect if javascript is not available

your solution clearly cannot work, since php is executed before the page is served on client

you could instead do something like

<noscript>
<meta http-equiv="refresh" content="0;URL='http://example.com/'">
</noscript>

in the head of your document

Anyway to detect whether user close the browser using php?

Not just with PHP.

PHP runs server-side, and is far done processing your page by the time the user will have a chance to close their browser. You could technically detect if PHP was still processing the page and the user closes it, with a specific configuration. However, it is not ideal. See connection_aborted().

What you need to do is set up a long-polling connection with JavaScript, and monitor it server-side. You will then get an idea for when that window is closed. That connection could be made to your PHP script, allowing PHP to check connection_aborted(). Note that you will need to set up ignore_user_abort() for this to work, or configure PHP.ini accordingly.

How to detect if JavaScript is disabled?

I assume you're trying to decide whether or not to deliver JavaScript-enhanced content. The best implementations degrade cleanly, so that the site will still operate without JavaScript. I also assume that you mean server-side detection, rather than using the <noscript> element for an unexplained reason.

There is no good way to perform server-side JavaScript detection. As an alternative it is possible to set a cookie using JavaScript, and then test for that cookie using server-side scripting upon subsequent page views. However this would be unsuitable for deciding what content to deliver, as it would not distinguish visitors without the cookie from new visitors or from visitors who did not accept the JavaScript set cookie.

file does not load properly according to visitor location

As many have pointed out, you've probably mixed up how server and client side resources are fetched. You need to understand that, all the code in the php side of things is compiled and evaluated into valid html when you submit a request for that resource.

Once the page renders in your browser, javascript comes into action. If you still want to include specific php files as per country code, you would have to make appropriate requests to the server.

So in your case since you are fetching the country code in javascript, you might want to make a request to another php script (let's call it foo.php) using a POST or GET request. You can then include the appropriate files for separate countries in a very similar switch statement. Only this switch statement would lie in foo.php. So foo.php could look something like this:

 <?php
$country= $_POST['countryid']; //Assuming you are making a post request and passing 'countryid'

switch ($country) {
case "UK":
include( "../../uk.php");
break;
case "US":
include( "../../us.php");
break;
case "PH":
include( "../../ph.php");
break;
default:
//if you want to handle this case..
}
?>

The ajax request could simply be:

  var country = geoplugin_countryCode();

...

$.ajax({
type: "POST",
url: "foo.php",
data: { countryid: country}
})
.done(function( msg ) {
//Ajax request completed
});

If you are unclear on how to make a post or get request and pass data along with it, I suggest reading up some documentation on ajax. Anyway, this is just one of the many ways you can get around your problem. Hope it gets you started in the right direction.

.htaccess Open main page if file or folder doesn't exist, but keep URL + URL Routing

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.+)$ index.html?url=$1 [QSA,L]

My problem with this that however it opens the main page every time, I
can't find the query (?url=) anywhere, so I can't use it.

This is an internal rewrite on the server. Consequently, the url URL parameter (present only on the internal rewrite) is only available to a server-side script, not client-side JavaScript. The browser/client only sees the response from the server - it is not aware of what file produced that response. However, client-side JavaScript can see what is present in the browser's address bar, which is accessible via the window.location object.

So, you can instead simplify the RewriteRule directive:

RewriteRule . index.html [L]

And in your JS you can read the requested URL-path from the window.location.pathname property. For example, if you request example.com/foo then the pathname property contains /foo (with a slash prefix) for you to act on accordingly in your script.

I still want 404 for all of the non existing subpages. How can I achieve it?

You can't if you are only using client-side JavaScript. A "404 Not Found" status is an HTTP response sent from the server.

The best you can do in client-side JS is to display what looks-like a "404 Not Found" message to the user and make sure you have a robots meta tag that prevents indexing. But this is still served with a 200 OK HTTP status. Search engines (ie. Google) will likely see this as a soft-404 (ie. a page that looks like a 404, but is served with a 200 OK status).

If you want to serve a 404 HTTP response status then the server would need to be aware of which are valid/invalid URLs.



Related Topics



Leave a reply



Submit