5

I'd like to emphasize where a web application is loaded from: the local development environment vs a test or production environment. To keep things simple, the mechanism should work just on CSS. But so far my CSS is a static file.

Is it possible to write a CSS that evaluates on the browser what background color to use, maybe based on the URL it was loaded from (localhost vs other hosts)?

Somehow I am hoping to get a solution based on CSS Conditional Rules.

Queeg
  • 7,748
  • 1
  • 16
  • 42

2 Answers2

5

I don't think this is possible using CSS, however you can do this using JavaScript. Checking if the current URL that is visited contains a certain string. Then changing style, you can also of course add a class within the if statement.

If you were to run this snippet in the answer it is blue, if you run this snippet on your localhost it will be red.

if (window.location.href.indexOf("stackoverflow") > -1) {
  document.body.style.backgroundColor = 'red';
} else {
  document.body.style.backgroundColor = 'blue';
}

The following screenshots will show how it effectively changes the background color based on the URL entered in the browser.

Without localhost in the name; enter image description here

With localhost in the name; enter image description here

To ignore everything that comes after the hostname and only take a look at the hostname and port you can use location.host seen in the following snippet.

if (window.location.host.indexOf("localhost") > -1) {
  document.body.style.backgroundColor = 'red';
} else {
  document.body.style.backgroundColor = 'blue';
}
FUZIION
  • 1,606
  • 1
  • 6
  • 19
1

While the accepted answer is the correct one to my question, I found a solution that I want to share with others and possibly my future self.

Since in Vaadin 8 it is not possible to directly add JavaScript into the generated HTML output (see here and here) it was easier for me to change the application slightly.

So in the application I added code like this. I am aware it does not check if the request was going to localhost - yet it checks that the client is on the same machine as the server, which essentially means the same.

public class App extends UI implements View {

    @Override
    protected void init(VaadinRequest request) {
        if ("127.0.0.1".equals(request.getRemoteAddr()) || "localhost".equals(request.getRemoteAddr())) {
            this.addStyleName("dev-environment");
        }
    }
}

Now as there is a new CSS class name in use, a simple tweak on the CSS did the trick:

// emphasize we are on localhost. The application sets the class name 'dev-environment' in this case
.dev-environment {
    background-color: #EEF0FF;
}
Queeg
  • 7,748
  • 1
  • 16
  • 42