Redirect link depending on JSON callback information

I experimented with utilizing JavaScript to automatically redirect website visitors based on their country.

The code snippet below demonstrates how the visitor's IP is checked to determine their country, such as CN for China, and then redirects them to another website accordingly.

<script async src="https://get.geojs.io/v1/ip/country.js"></script>

<script type="application/javascript">
  function geoip(json) {
    var userCountry = json.country;
  }

  if (userCountry == "CN") {
    window.location = "http://baido.com";
  }
</script>

Can anyone provide any guidance or assistance?

Answer №1

Although there is a marked solved answer, I still struggled to make it work. As an alternative, I came up with this solution:

  function geoip() {
  
   $.ajax({
        type: 'get',
        url: 'https://get.geojs.io/v1/ip/country.json',
        success: function(data) {
            if (data['country'] == "CN") {
              window.location = "https://baido.com/";
            }
    }
    });
    }
    
geoip();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Answer №2

It seems that the issue lies in how you are using the provided code example. The countrycode.textContent section is designed to display the user's country code in the browser, so it may not suit your specific needs if you are attempting a redirect.

Additionally, keep in mind that the geoip function is utilized by the script linked from geojs, meaning any redirection should be implemented within that function.

Below is an enhanced version of the code that should fulfill your requirements:


    <script type="application/javascript">
        function geoip(json){
            if (json.country_code == "CN") {
              window.location = "http://baido.com/";
            }
        }
    </script>
    <script async src="https://get.geojs.io/v1/ip/geo.js"></script>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Utilize Jquery to calculate the total sum of values associated with a particular key in a JSON object based on input

I am facing an issue with my script where I am trying to sum up the clientPrice keys in a JSON object assigned to a form text element. Here is what I have: <input id="clientList" type="hidden" value="[{"clientID":"1","clientType":"0","clientPrice":"450 ...

React Big Calendar - Creating a personalized property for a unique perspective

My React Big Calendar library has a custom view for the year. <Calendar localizer={localizer} events={events || []} startAccessor="start" endAccessor="end" defaultView="year" views={{ year: YearView }} c ...

Modifying the image height in a column using Bootstrap and JSON data

My webpage is dynamically generating images from a JSON file through a JavaScript file. However, the images are displaying at different heights, and I want each column to adjust to the height of the image to eliminate any gaps. Particularly, data with the ...

React - Refreshing a component with the help of another component

I've created a NavBar component that contains a list of links generated dynamically. These links are fetched from the backend based on specific categories and are stored within a child component of NavBar named DrawerMenu. The NavBar itself is a chil ...

Can someone assist me in retrieving the current date from the epoch? I am currently receiving the date as January 19, 1970

Obtain the review date from a JSON object and format it: String datetime = jsonObject.getString("ReviewDate"); datetime = datetime.replace("Date(", "").replace(")", "").replaceAll("/", ""); Long ldate = Long.valueOf(datetime); Date date ...

The robot will automatically update its own message after a designated period of time

I am facing an issue with my code where the bot is not updating its message after a specific time period defined by time.milliseconds * 1000. How can I make the bot edit its message after that duration? let timeout = 15000; if (author !== null && ...

Why does modifying a variable within the fetch URL result in undefined

I currently have a server running on the URL http://localhost:3000/. Within my JavaScript code, I have defined a variable called productCode with the value 'example-code55'. let productCode = 'example-code55'; const fetchData = async ...

Having difficulty identifying the same element during testing

Here is the code snippet I'm working with, which checks for expected text: console.log(typeof browser.getText('.modal.modal--primary.pin-container h1')); expect(browser.getText('.modal.modal--primary.pin-container h1')).toContain( ...

Numerical values are not considered by the JavaScript table filter

I'm having trouble with dynamically filtering the content. It works fine for the first two columns, but not for the third one. Maybe I need some additional JavaScript? Here is the link to my snippet: `https://www.w3schools.com/code/tryit.asp?filen ...

Redux: Double rendering issue in mapStateToProps

I've recently delved into learning Redux, and I've encountered an issue that's been on my mind. import React, { useEffect } from "react"; import { connect, useDispatch } from "react-redux"; import Modal from "../Moda ...

How to implement datepicker on multiple input fields

Below are the two input fields that have datepicker functionality: <div class="row"> <input type="text" class="form-control" datepicker-popup="{{format}}" ng-model="dt" is-open="opened" min="minDate" max="'2015-06-22&apos ...

What similarities are present in those properties in the JSON file?

Upon receiving this json using the POST method, I am trying to create an object. However, I am confused about how to proceed with this code. Why are there multiple properties with the same name? Are they objects of different classes within the fields cla ...

What is the best way to customize a MaterialUI outlined input using a global theme overrides file?

I've been working on customizing my theme file with overrides, and I've encountered a strange bug while trying to style the outlined input. It seems like there are two borders appearing when these styles are implemented. https://i.stack.imgur.co ...

Can you explain the significance of argument[0] in JavascriptExecutor?

I recently implemented the "How to handle hidden web elements using the JavaScript executor method". However, I am still unclear about how the method works. public static void selectDateByJS(WebDriver driver, WebElement element, String dateVal) { Javas ...

Encountering a 401 Error while trying to host an Angular app on Google Cloud Storage

I am currently facing an issue with deploying my Angular app to a Google Cloud Storage bucket. The bucket is public and set up to be served as a custom website via CNAME (test.example.com). The main page and 404 handler are mapped to index.html, but I am e ...

Transmitting encoded bytes data via JSON

Currently, I am developing a Python RESTful API and facing the challenge of transmitting bytes-encoded data (specifically encrypted data using a public RSA key from the rsa package) over the network in JSON format. This is what the scenario looks like: & ...

Encountering issue while static generating project: Cannot find resolution for 'fs' module

I am encountering an issue in my Next.js app when trying to serve a static file. Each time I attempt to use import fs from 'fs';, an error is thrown. It seems strange that I have to yarn add fs in order to use it, as I thought it was not necessa ...

Implementing Server-Side Python (GAE) for Parameter Processing without jQuery $.param

Currently, I am utilizing jQuery's $.post() feature to send JSON data, particularly an array. $.post('/my/url/',{my_list:['foo','bar','foo baz']}) After reading the documentation, it mentions that the post met ...

Using JQuery to switch out images that do not have an ID or class assigned

Currently, I am using a Google Chrome Extension to apply an external theme to a website. Unfortunately, the logo on the site does not have an ID or class that can be used to call it. I am searching for a solution to replace it with a different image. My ...

By incorporating JavaScript, clicking on an image will trigger a shift in the position of a different element

Just starting out with JavaScript and experimenting with creating an event where clicking on an image triggers the movement of another hidden image. The hidden image is positioned off-screen to the left, while there is a table of images in the center of th ...