Ishan
Ishan

Reputation: 4339

Return different response from the browser when the User Agent is curl

How do I return a different response from the browser when the user agent is curl using javascript?

for eg:

if user agent is curl
 return /feed.json
else
 return index.html

This is the code that I have, but when i run the command curl http://example.com it just returns the html response

<script>
      function browserRedirect(){
        var userAgent = navigator.userAgent.toLowerCase();
        console.log(userAgent);
        var curl = userAgent.match(/curl|PycURL/i) == "curl";
        var chrome = userAgent.match(/chrome/i) == "chrome";

        // Check that the user agent is curl
        if(curl) {
          window.location.href = "/feed.json"
        }
      }

      browserRedirect()
</script>

Upvotes: 1

Views: 1134

Answers (1)

ablopez
ablopez

Reputation: 850

The code you're using won't work as you're trying to use a Javascript-based redirect on a Javascript-less environment which is curl, and even if you do it, curl won't follow the redirect as curl just returns the HTTP headers and response as-is, and the redirect is just an HTTP header.

Rather than using redirects, you should be outputting a different MIME type (in the HTTP headers) and different output content depending on the user agent.

For example, if by default your page returns HTML (and thus a text/html MIME type), if the user agent header received matches the "curl" regexp you're using, you should be sending a "Content-type: application/json" HTTP header for the MIME type, and output the content from your feed.json file instead of the default HTML output of your page and terminate the execution of your page there. Thus, this code should be placed at the very beggining of your server-side code.

BTW, as an observation to your Javascript code without taking into account this context, the IF block never runs because match() returns an array of string matches (rather than a single string), or null if the match is not found. If it were the case of a user-agent-based redirect for a standard browser with Javascript support, you should change your code to something like if(navigator.userAgent.match(/safari/i)){ // Code goes here } (using Safari as matching browser in this example). Also note that the call to toLowercase() is not needed as you're already doing a case-insensitive search by using the "i" flag at the end of the regexp.

Upvotes: 1

Related Questions