Skip to main content

Pull the users IP address

This guide explains how an iFrame can be used to pull the IP address of the user currently using a Superblocks Application.

  1. Drag and drop an iFrame component to the Canvas of your Superblocks Application.

  2. Copy and paste the following code-snippet to the Source Doc property of the iFrame

    The code adds a button to the iFrame component. When the button is clicked it performs an HTTP GET request to ipify, an IP address API, using the Axios library.

    The IP address is then communicated from the iFrame back to the parent window object (your Superblocks Application) via the Window.postMessage() method:

    <html>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.19.2/axios.min.js"></script>
    <body>
    <input type="button" value="Get IP"/>
    <script>
    document.querySelector('input')
    .addEventListener('click', () => getIP(), false)

    async function getIP(){
    let url = 'https://api64.ipify.org/?format=json';
    const { data } = await axios.get(url);

    parent.postMessage({
    value: data,
    }, "*");};

    </script>
    </body>
    </html>

    In the image below the code snippet was pasted to the pop-out editor that expands the editor into a tab in the bottom panel:

    JavaScript code was pasted into the source doc property of an iFrame component
  3. Open the settings for the onMessageReceived event handler and add a Run JS (in browser) action type to it

  4. Copy and paste the following JavaScript code to the Run JS action type

    The code stores the IP address returned by the iFrame in a Frontend Variable called myip via the storeValue() function:

    storeValue("myip",currentMessage);
    The onMessageReceived event handler was used to store the IP address in a frontend variable
  5. Drag and drop a text component to the Canvas of your Superblocks Application

  6. Copy and paste the following snippet into the Text property of the text component

    The snippet makes use of frontend bindings to pull the IP address stored in the global object:

    The IP is: <b>{{Global.store.myip.value.ip}}</b>
    The IP address is pulled from the frontend variable via frontend bindings
  7. Click the button to show the IP address in the text component

    Pull the IP address on page load‚Äč

    Replace the previous JavaScript code pasted to the Source Docs with the following snippet to pull the users IP address on page load. In this case the click on the button is not necessary and the iFrame would remain empty:

    <html>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.19.2/axios.min.js"></script>
    <body>
    <script>
    async function getIP(){
    let url = 'https://api64.ipify.org/?format=json';
    const { data } = await axios.get(url);

    parent.postMessage({
    value: data,
    }, "*");
    };
    window.onload = getIP;
    </script>
    </body>
    </html>