How-to: Target particular pages

The CSS/JS for your prototype is injected on every page of the website. But what if you want to apply your changes only to a particular page or set of pages?

Method 1 — Look for existing hooks in the HTML

It is likely that the site already has some classes/IDs for targeting pages or sections. For example, their login page might already have a class on the body tag:

<body class='login-page'>

Then you can easily target your css using that body class:

.login-page h1 {
  text-transform: uppercase;
}

However, watch out as this can be error prone, as the target site may not be consistent. For example, that .login-page class might also be used on the signup or password reset pages.

Method 2 — Use JS to add your own hooks

The more reliable method to target pages is to create your own hooks. Then you can be sure that your overrides will target the right pages while leaving others untouched.

The key is to create a new script in Labcoat that adds your hooks based on the URL. The window.location object in Javascript provides access to all the elements of the URL.

For example, when searching on Mozilla’s Developer Network, you might get the following.

url = window.location
console.log(url.href);      // https://developer.mozilla.org/en-US/search?q=URL#search-results-close-container
console.log(url.hostname);  // developer.mozilla.org
console.log(url.pathname);  // /en-US/search
console.log(url.search);    // ?q=URL
console.log(url.hash);      // #search-results-close-container

For a complete reference, view the documentation on window.location on MDN.

Armed with this information, then in your script compare against these properties and add any behaviour or styling you want:

// page matches exactly
if (window.location.pathname == '/login') {
  $('body').addClass('labcoat-login-page')
}

// check if the page is in the About section
if (window.location.pathname.startsWith('/about')) {
  // redirect to a local site
  window.location = 'http://localhost:3000/about.html'
}

// check if the user has searched for "widget"
if (window.location.search.toLowerCase().includes("widget")) {
  // insert a new search result
}


Do you have any suggestions for how to improve this (or any) documentation?
Send an email to support@labcoat.io