Subroutines frontend / backend

How to create a subroutine in the frontend?
Although it is a good practice to put subroutines used on different pages in the backend, I have a problem with a specific request.
I need to capture some info (like the ip adress) from where the user call the page.
I use the routine using a fetch from ipinfo.io and get some info from the IP provider.
BUT, if I put this routine as a backend repcess, I receive the info of the wix server provider !!!.

const request = await fetch(“https://ipinfo.io/?token=Mytoken”)
const jsonResponse = await request.json()*
let comments = jsonResponse.org + ", " + jsonResponse.hostname*
console.log(jsonResponse.ip)*
console.log(jsonResponse.hostname) //“hostname”: “host-95-182-162-132.dynamic.voo.be”,*
console.log(jsonResponse.org) //“org”: “AS12392 VOO S.A.”,*

Putting these lines of code on a page (ie in the frontend) gives me the correct information I need.
Is there a way to “put” this somewhere as a routine and be abble to call it from different pages as if it was executed in the frontend?

Hi,

If I well understand your need, you could put this code in masterPage.js .

But your code will be launched each time, you load a page.

To avoid this you could use a session variable, you check before launching your code as this :
$w.onReady(async function () {
const Init = session.getItem(“Init”);
//
if (!Init && !InitOnGoing) {
InitOnGoing = true;
initData();
Init = session.setItem(“Init”,“1”);
}
InitOnGoing = false;
});

regards,

Hi, sentiers5140 !!

Placing functions (subroutines) in a public .js file and then calling them—would this approach not meet the requirements? :thinking:

Thanks. No sure to I understand what you mean by a public .js file?
Where to put this file? in Wix, somewhere else?

Please look for this icon on the left side of the editor: { }. When you click on that icon, you should find words like “Public” or “Backend.” If you want to organize functions to be called from the frontend, you can add a new .js file in the Public section and write the functions in that file. For more details, refer to the following link—it’s very helpful and easy to understand! :wink:

1 Like

Not sure it will work as I need.
I want something that could be executed at some events
Lets have an exemple
On a page, there are some informations displayed and some buttons that could bring the user to other informations.
For some of those links (not all), I want to execute a function
for exemple,
a page with a repeater, on each element of the repeater, there are some links. For one of these link, I want to have information about the user location (through the ipinfo ) .
This is important for adapting our communication campaigns.
Any other idea

A normal function in public or backend file will do the job.
In this function you read your data and do what you want.