Home > Net >  Different background color depending on URL
Different background color depending on URL

Time:11-24

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 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';
}

CodePudding user response:

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;
}
  •  Tags:  
  • css
  • Related