I would like to get a lightbox open if the user is not from a specific country. For example, on our Canadian website, we would like a lightbox open for all the users who come from another country…
I’m trying the following code without success :
import { fetch } from ‘wix-fetch’ ;
import wixWindow from ‘wix-window’ ;
$w . onReady ( function () {
// Fetching the user’s location details
[fetch](fetch('https://ipapi) [(](fetch('https://ipapi) ['https://ipapi](fetch('https://ipapi) . co/json ’ , {
method : ‘get’
})
// Check if the request was successful
. then (( httpResponse ) => {
if ( httpResponse . ok ) { return httpResponse . json ();
}
})
. then (( json ) => {
// Set the user’s countryCode as a const
const loc = json . countryCode ;
/* Check if country code is of Canada */
if ( loc === “CA” ){
// Stay on this URL
} else {
wixWindow . openLightbox ( “CountryRedirectLightbox” );
}
});
})
I just tested the API. Neat tool. I might actually use that on a project I am working on. I did notice that the returned object lists the country code as country_code instead of countryCode. Updating that in your code should solve the issue.
@amotor It works perfectly… The only issue i’m facing now, is that, if the person decide to stay on the website anyway by clicking the button to close the lightbox, the lightbox comes up each time the user is changing page… Do you know any way to prevent the lightbox to comes up again if the user has decided to stay on the website ? But i’m pretty shure this aprt of code should be on my master page… Thank you again !
Here is the code on my lightbox page :
import wixWindow from ‘wix-window’ ;
$w . onReady ( function () {
$w ( ‘#button6’ ). onClick ( function () {
wixWindow . lightbox . close ( “Website Redirect” );
@amotor Oh this is already disable. The code on the masterpage is making the lightbox appearing if the user is not from Canada. So if he decide to stay on the website anyway and change page, the code runs again beacause he’s still not from Canada… So this is a code fix for sure…
@y-dorey you can set a session variable if the user chooses to stay on the page and then check if the variable exists before running the code that renders the lightbox.
import {session} from "wix-storage"
...
$w("#button6").onClick(function() {
session.setItem("userConfirm", true)
wixWindow.lightbox.close("Website Redirect");
}
...
$w.onReady(function(){
let userConfirm = session.getItem("userConfirm")
if(userConfirm !== true) {
fetch('https://ipapi . co/json',{method: 'get' })
//rest of your code here
}
}
@amotor Thanks again for your precious help! Sorry, I’m not very experienced in coding, I’m learning on the fly. Here is how I have integrated your solution on the masterPage :
import { fetch } from ‘wix-fetch’ ;
import wixWindow from ‘wix-window’ ;
import { session } from “wix-storage” ;