javascriptweb-scrapingtampermonkey

JavaScript function to get Instagram ID


I have a JavaScript function with an event button to get ID of instagram users, but the problem is that it will only get the ID of the first user, and if I try to go to another profile, it gives the ID of the old profile, instead of getting of the current page profile?

(function() {
    'use strict';

    // Function to extract profile ID from the Instagram page
    function getProfileId() {
        // Extracting profile ID from the page source
        var pageSource = document.documentElement.innerHTML;
        var profileIdPattern = /"profilePage_(\d+)"/;
        var matches = pageSource.match(profileIdPattern);
        if (matches && matches.length > 1) {
            return matches[1];
        }
        return null;
    }

    // Function to copy text to clipboard
    function copyToClipboard(text) {
        GM_setClipboard(text, 'text');
    }

    // Function to create and append a copy button to the Instagram page
    function createCopyButton() {
        var button = document.createElement('button');
        button.textContent = 'Copy Profile ID';
        button.style.position = 'fixed';
        button.style.top = '20px';
        button.style.right = '20px';
        button.style.zIndex = '9999';
        button.style.padding = '10px';
        button.style.border = 'none';
        button.style.backgroundColor = '#3897f0';
        button.style.color = '#fff';
        button.style.cursor = 'pointer';
        button.addEventListener('click', function() {
            var profileId = getProfileId();
            if (profileId) {
                copyToClipboard(profileId);
                console.log('Profile ID copied to clipboard:', profileId);
                alert('Profile ID copied to clipboard:\n' + profileId);
            } else {
                console.log('Profile ID not found.');
                alert('Profile ID not found.');
            }
        });
        document.body.appendChild(button);
    }

    // Run the function to create the copy button when the page is loaded
    window.addEventListener('load', createCopyButton);

})();

How do I fix it such, that it reloads everytime I go try get the ID of a new profile after the first one?


Solution

  • The user_id is not always present in the page's html, you'll have to use the api for a consistent result. to keep modifications minimal, you could replace the getProfileId function with this:

    function getProfileId() {
        const username_div = document.querySelector('header > section > div:first-child > div:first-child'); // this div should contain the user handle
        if (!username_div) return;
        const url = `https://www.instagram.com/api/v1/users/web_profile_info/?username=${username_div.textContent}`;
        const request = new XMLHttpRequest();
        request.open('GET', url, false); // synchronous request
        request.setRequestHeader('x-ig-app-id', '936619743392459'); // important header, will get error(400) without it
        request.send();
        const obj = JSON.parse(request.responseText);
        return obj.data.user.id;
    }
    

    if you want to use fetch, you'll have to use a callback or change your functions to use async/await.

    Also, you might want to show the button only on profile pages, perhaps by listening for navigation events.

    eg: window.navigation.addEventListener('navigatesuccess', () => setTimeout(toggleButton, 1000))

    toggleButton could be something like this:

    function toggleButton(){
        const button = document.querySelector('#get-id');
        const target = document.querySelector('header > section > div:first-child');
        button && (button.style.visibility = target ? 'visible' : 'hidden');
    }
    

    and make sure to add these lines at the end of the createCopyButton function:

    button.id = 'get-id';
    toggleButton();