Skip to content
  • There are no suggestions because the search field is empty.

HTML 5 Geolocation

Use HTML5 Geolocation in Convert for Browser-Based Location Targeting

 THIS ARTICLE WILL HELP YOU:


Overview

Convert can already target visitors by country, region or city from their IP address. We recommend you use that first. Use the browser's HTML5 geolocation only when IP geolocation does not meet your needs.

This article shows how to find the visitor's country with HTML5 geolocation and Google's Geocoding service, and how to target an experience on it. The visitor's position is only known after they allow it, so the experience waits with the When a callback is called Location trigger. This replaces the legacy convert_recheck_experiment() token, which is being phased out. The developer docs cover the same switch in Migrate to Dynamic Location Triggers.

Advantage

The browser works out the position itself, so it does not depend on IP databases. Those databases can be out of date, and one IP address can be shared across regions. Some browsers still use an IP lookup in some cases.

Disadvantage

  • The browser asks the visitor for permission to share their location. The location only exists after the visitor allows it. If they block it or ignore the prompt, there is no location, and the experience does not run for them.
  • Until the visitor answers, they see the original page.
  • Browsers only offer geolocation on secure (HTTPS) pages.
  • Turning the position into a country uses Google's Geocoding service, which counts toward your Google Maps Platform usage. The helper below remembers the result for the browser session, so it looks up each visitor once per session.

This might not suit every type of experience.

Before you start

Load the Google Maps JavaScript API

Load the Google Maps JavaScript API with your API key on every page where the experience runs. Load it before the Convert tracking code, so it is ready when the experience needs it. Google describes the ways to load it in Load the Maps JavaScript API. The helper below works with the script tag and with dynamic library import.

If the Maps script loads later, the helper waits up to about 5 seconds for it. If it still hasn't loaded by then, the experience does not run on that page view.

The example in this article targets visitors in Mexico. Change the country code to target another country, or use the region to target a state or province.

Add the geolocation helper to your Project Global JS

In your project, go to Configuration > Global Javascript and add this helper. You only need to add it once per project. It does not ask for the visitor's position when the page loads. It asks only when the callback below calls it, and then:

  1. asks the browser for the visitor's position,
  2. waits for the Google Maps script if it hasn't loaded yet (up to about 5 seconds),
  3. turns the position into a country and region with Google's Geocoder,
  4. stores the result in window.html5Geo as country, countryCode and region,
  5. remembers it for the browser session, so later pages don't ask or look it up again.

Save it under All Environments. If one of your environments has its own Global JS, add the helper there too, because that script replaces the All Environments code on that environment.

(function () {
var cacheKey = 'convertHtml5Geo';
var pending = null;

try {
window.html5Geo = window.html5Geo || JSON.parse(window.sessionStorage.getItem(cacheKey));
} catch (e) {
window.html5Geo = window.html5Geo || null;
}

var readAddress = function (results) {
var geo = { country: '', countryCode: '', region: '' };
var parts = (results && results[0] && results[0].address_components) || [];
parts.forEach(function (part) {
if (part.types.indexOf('country') > -1) {
geo.country = part.long_name;
geo.countryCode = part.short_name;
}
if (part.types.indexOf('administrative_area_level_1') > -1) {
geo.region = part.long_name;
}
});
return geo.countryCode ? geo : null;
};

// Wait up to about 5 seconds (100 ms x 50) for the Google Maps script.
var waitForMaps = function () {
return new Promise(function (resolve) {
var tries = 0;
var check = function () {
var maps = window.google && window.google.maps;
if (maps && (maps.importLibrary || maps.Geocoder)) return resolve(maps);
if (tries >= 50) return resolve(null);
tries++;
setTimeout(check, 100);
};
check();
});
};

var getGeocoder = function () {
return waitForMaps().then(function (maps) {
if (!maps) return null;
if (maps.importLibrary) {
return maps.importLibrary('geocoding').then(function (lib) {
return new lib.Geocoder();
});
}
return new maps.Geocoder();
});
};

var lookUp = function (coords) {
return getGeocoder().then(function (geocoder) {
if (!geocoder) return null;
return new Promise(function (resolve) {
var request = geocoder.geocode(
{ location: { lat: coords.latitude, lng: coords.longitude } },
function (results, status) {
resolve(status === 'OK' ? readAddress(results) : null);
}
);
if (request && request.catch) {
request.catch(function () {
resolve(null);
});
}
});
});
};

window.requestHtml5Country = function () {
if (pending) return pending;
pending = new Promise(function (resolve) {
if (window.html5Geo) return resolve(window.html5Geo);
if (!navigator.geolocation) return resolve(null);
navigator.geolocation.getCurrentPosition(
function (position) {
lookUp(position.coords).then(function (geo) {
if (geo) {
window.html5Geo = geo;
try {
window.sessionStorage.setItem(cacheKey, JSON.stringify(geo));
} catch (e) {}
}
resolve(geo);
}, function () {
resolve(null);
});
},
function () {
resolve(null);
},
{ timeout: 10000, maximumAge: 600000 }
);
});
return pending;
};

window.waitForHtml5Country = function (maxWait) {
return new Promise(function (resolve) {
setTimeout(function () {
resolve(null);
}, maxWait || 10000);
window.requestHtml5Country().then(resolve);
});
};
})();

If you change the helper, don't declare a variable whose name ends in "location" (for example geolocation). The Global Javascript syntax check can flag it as an error.

Set the Location trigger to wait for the visitor's country

Create your experience and its changes, if you have not done so.

Edit the experience's Location settings, choose When a callback is called as the trigger, and paste this code. Replace /your-store-page with the start of the path of the pages this experience targets, for example /stores:

if (options.isActive) return;

// Convert runs this code on every page that has the tracking code.
// Only ask for the visitor's position on the pages this experience targets.
// Replace '/your-store-page' with the start of your page's path.
if (window.location.pathname.indexOf('/your-store-page') !== 0) return;

window.waitForHtml5Country(10000).then((geo) => {
if (geo) {
activate();
}
});

Convert runs this callback on every page with the tracking code, before it checks the Location's page rules. If the callback asked for the position straight away, every page would show the permission prompt. That is why it first checks that the visitor is on a page this experience targets.

The callback then waits up to 10 seconds (10000 ms) for the visitor to answer and for the lookup to finish. If there is no result by then, the experience does not start on this page view. If the visitor allows the prompt later, the result is saved, and the experience can start on the next page they view.

Convert passes two arguments to the callback: activate, which you call when the experience should start, and options, which includes locationId and isActive. The isActive check stops the callback from running twice. For more on this trigger, see Targeting Experiments with Dynamic Location Triggers (JS Callbacks).

Create the audience

Edit the experience's audience settings, select New Audience, open the Advanced tab, and add a JS Condition with this code:

(function () {
var geo = window.html5Geo;
return !!geo && geo.countryCode === "MX";
})()

The condition compares the two-letter country code (MX for Mexico). To target a state or province, compare geo.region instead. Add the audience to your experience and save.

Run a QA in your experience

Test on an HTTPS page that matches your Location. After you allow the prompt, run this in the browser console:

window.html5Geo;

It should show something like:

{ "country": "Mexico", "countryCode": "MX", "region": "Jalisco" }

Then follow the QA guide. Test three cases: allow, block, and ignore the prompt. The result is kept for the browser session, so open a new private window for each test. Your browser's developer tools can simulate a location, for example the Sensors panel in Chrome.

If your plan doesn't include Dynamic Website Triggers (legacy)

Without Dynamic Website Triggers, you can use the legacy convert_recheck_experiment() token in the audience condition instead. The token is being phased out. It still works today, but use the callback trigger above if your plan includes Dynamic Website Triggers.

When the condition calls the token, Convert checks the experience again every 50 ms for about 2 minutes, then stops. If the visitor answers the prompt after that, the experience does not run on that page view. It can run from their next page view, because the helper keeps the result for the session.

Until the visitor answers the prompt, every page view keeps the re-checks running for those 2 minutes. Limit the experience's Locations to the pages where you need the position.

  1. Load the Google Maps JavaScript API and add the geolocation helper to your Global JS, as described above. Skip the callback.
  2. Keep the Location trigger set to Upon Run.
  3. Add this JS Condition to the audience:
(function () {
var geo = window.html5Geo;
if (!geo) {
if (window.requestHtml5Country) window.requestHtml5Country();
convert_recheck_experiment();
return false;
}
return geo.countryCode === "MX";
})()

The condition asks for the position the first time it runs. Convert checks the audience only on pages that match the experience's Location, so the permission prompt appears only there. Keep convert_recheck_experiment(); on its own line, as shown. The condition calls it only while there is no result. Once there is one, the condition returns true or false and the re-checks stop.

If your plan later includes Dynamic Website Triggers, move to the callback: change the Location trigger to When a callback is called, add the callback code, replace the condition with the one in Create the audience, and run a QA before you publish the change.