MetaMask no longer injects web3, please help me

I tried to add a connection to my code and in the console log it says, @ivan @cryptokid @Capplequoppe ```
inpage.js:1 MetaMask no longer injects web3. For details, see: https://docs.metamask.io/guide/provider-migration.html#replacing-window-web3
get @ inpage.js:1
login @ main.js:30
main.js:30 Uncaught (in promise) TypeError: Cannot read properties of undefined (reading ‘Contract’)
at HTMLButtonElement.login (main.js:30)
login @ main.js:30

This is the screenshot of the error below


Did you also include web3?

Here is an example:

i added this following line of code

async function login() {
    let user = Moralis.User.current();
    window.tokenContract = new web3.eth.Contract(tokenContractAbi, TOKEN_CONTRACT_ADDRESS);
    if (!user) {

This is the full code below

//LOGIN BUTTON
async function login() {
    let user = Moralis.User.current();
    window.tokenContract = new web3.eth.Contract(tokenContractAbi, TOKEN_CONTRACT_ADDRESS);
    if (!user) {
        try {
            user = await Moralis.authenticate({
                signingMessage: "Welcome to GrandPaDoge NFT MarketPlace",
            });
        } catch (error) {
            alert(
                (error = /*jshint -W022 */
                    "Please consider installing Metamask to connect to MrGrandPaDoge NFT MarketPlace")
            );
        }
    }
    console.log("logged in user:", user);
    hide_buttons();
    const isWeb3Active = Moralis.ensureWeb3IsInstalled();

    if (isWeb3Active) {
        //const chainId = 43114;
        //const chainName = "Avalanche Mainnet";
        //const currencyName = "AVAX";
        //const currencySymbol = "AVAX";
        //const rpcUrl = "https://api.avax.network/ext/bc/C/rpc";
        //const blockExplorerUrl = "https://cchain.explorer.avax.network/";

        //await Moralis.addNetwork(
        //chainId,
        //chainName,
        //currencyName,
        //currencySymbol,
        //rpcUrl,
        //blockExplorerUrl
        //);
        console.log("Activated");

    } else {
        {
            enable();
            await Moralis.enable();
        }
    }
}

// LOGOUT BUTTON
async function logOut() {
    await Moralis.User.logOut();
    console.log("logged out");
    hide_buttons();
}

In your html code you have to include web3 similar to how you include Moralis sdk

Are you talking about this bro? @cryptokid

yes, about that, it looks like it has web3 there in html head

Yes it is there what should i do bro?

you could try to add web3 = await Moralis.enableWeb3() before that line

Okay bro, thank you i will add it now

After adding the line, i got this error bro, please help bro @cryptokid

main.js:216 Uncaught (in promise) ReferenceError: user is not defined
    at HTMLButtonElement.openCreateItemButton 

you have to look where from is that error, look at the line that generates that error, try to see why that variable is undefined

I have looked on it but i am finding it difficult to understand why user is not define in that line of code

check how that user variable was defined before that line of code

This is my main.js code

const serverUrl = "https://m6dzfhl2ot7y.usemoralis.com:2053/server";
const appId = "VsOmsC3GSBUsbLDUK2ocfo8l66kYdXfVaZUWwMiF";
Moralis.start({ serverUrl, appId });
const TOKEN_CONTRACT_ADDRESS = "0x51e7b6E77B9fa3F3B525161c5eDfCF1C8Df32818";

// Moralis Connection
async function hide_buttons() {
    let user = await Moralis.User.current();
    if (!user) {
        document.getElementById("btnConnect").style.display = "block";
        document.getElementById("btnUserInfo").style.display = "none";
        document.getElementById("btnLogout").style.display = "none";
        document.getElementById("userInfo").style.display = "none";
        document.getElementById("btnOpenCreateItem").style.display = "none";
        document.getElementById("createItem").style.display = "none";
    } else {
        document.getElementById("btnUserInfo").style.display = "block";
        document.getElementById("btnConnect").style.display = "none";
        document.getElementById("btnLogout").style.display = "block";
        document.getElementById("btnOpenCreateItem").style.display = "block";
        document.getElementById("createItem").style.display = "none";
    }
}

hide_buttons();

//LOGIN BUTTON
async function login() {
    web3 = await Moralis.enableWeb3();
    window.tokenContract = new web3.eth.Contract(tokenContractAbi, TOKEN_CONTRACT_ADDRESS);
    let user = Moralis.User.current();
    if (!user) {
        try {
            user = await Moralis.authenticate({
                signingMessage: "Welcome to GrandPaDoge NFT MarketPlace",
            });
        } catch (error) {
            alert(
                (error = /*jshint -W022 */
                    "Please consider installing Metamask to connect to MrGrandPaDoge NFT MarketPlace")
            );
        }
    }
    console.log("logged in user:", user);
    hide_buttons();
    const isWeb3Active = Moralis.ensureWeb3IsInstalled();

    if (isWeb3Active) {
        //const chainId = 43114;
        //const chainName = "Avalanche Mainnet";
        //const currencyName = "AVAX";
        //const currencySymbol = "AVAX";
        //const rpcUrl = "https://api.avax.network/ext/bc/C/rpc";
        //const blockExplorerUrl = "https://cchain.explorer.avax.network/";

        //await Moralis.addNetwork(
        //chainId,
        //chainName,
        //currencyName,
        //currencySymbol,
        //rpcUrl,
        //blockExplorerUrl
        //);
        console.log("Activated");

    } else {
        {
            enable();
            await Moralis.enable();
        }
    }
}

// LOGOUT BUTTON
async function logOut() {
    await Moralis.User.logOut();
    console.log("logged out");
    hide_buttons();
}

// OPEN USER INFO FIELD
async function openuserInfo() {
    const user = Moralis.User.current();
    hide_buttons();
    console.log("User Profile Opened ");
    if (user) {
        const email = user.get("email");
        if (email) {
            userEmailField.value = email;
        } else {
            userEmailField.value = "";
        }
        userUsernameField.value = user.get("username");
        const userAvatar = user.get("avatar");

        if (userAvatar) {
            console.log(userAvatar);
            imgAvatar.src = userAvatar.url();
            document.getElementById("imgAvatar").style.display = "block"; //display avatar
        } else {
            document.getElementById("imgAvatar").style.display = "none"; //hide avatar when user is connected
        }
        document.getElementById("userInfo").style.display = "block"; //Hide userinfo
    } else {
        login(); //if not,then login
    }
}

// SAVE USER INFO FIELD
async function saveUserInfo() {
    let user = await Moralis.User.current();

    user.set("email", userEmailField.value);
    user.set("username", userUsernameField.value);

    if (fileAvatar.files.length > 0) {
        //get user avatar
        const avatar = new Moralis.File("avatar.jpg", fileAvatar.files[0]);
        console.log(fileAvatar.files);
        x = await avatar.save();
        console.log(x);
        user.set("avatar", x);
    }

    alert("User info saved successfully!");
    console.log("User Info Saved");
    openuserInfo();
}

async function closeuserInfo() {
    user = await Moralis.User.current();
    hide_buttons();
    if (user) {
        document.getElementById("userInfo").style.display = "none";
        console.log("User Info closed");
    } else {
        logOut();
    }
}

async function createItem() {
    if (createItemFile.files.Length == 0) {
        alert("Please select a file!");
        return;
    } else if (createItemNameField.value.length == 0) {
        alert("Please give the item a name!");
        return;
    }

    const nftFile = new Moralis.File("nftFile.jpg", createItemFile.files[0]);
    await nftFile.saveIPFS();

    const nftFilePath = nftFile.ipfs();
    const nftFileHash = nftFile.hash();

    const metadata = {
        name: createItemNameField.value,
        description: createItemDescriptionField.value,
        image: nftFilePath,
    };
    const nftFileMetadataFile = new Moralis.File("metadata.json", {
        base64: btoa(JSON.stringify(metadata))
    });
    await nftFileMetadataFile.saveIPFS();

    const nftFileMetadataFilePath = nftFileMetadataFile.ipfs();
    const nftFileMetadataFileHash = nftFileMetadataFile.hash();

    const nftId = await mintNft(nftFileMetadataFilePath);

    const Item = Moralis.Object.extend("Item");


    // Create a new istance of that class
    const item = new Item();
    item.set('name', createItemNameField.value);
    item.set('description', createItemDescriptionField.value);
    item.set('nftFilePath', nftFilePath);
    item.set('nftFileHash', nftFileHash);
    item.set('MetadataFilePath', nftFileMetadataFilePath);
    item.set('MetadataFileHash', nftFileMetadataFileHash);
    item.set('nftId', nftId);
    item.set('nftContractAddress', TOKEN_CONTRACT_ADDRESS);
    await item.save();
    console.log(item);
}

mintNft = async(metadataUrl) => {
    const receipt = await tokenContract.methods.createItem(metadataUrl).send({ from: ethereum.selectedAddress });
    console.log(receipt);
    return receipt.events.Transfer.returnValue.tokenId;
};

// NavBar OnClick Buttons
document.getElementById("btnConnect").onclick = login;
document.getElementById("btnLogout").onclick = logOut;

// USER PROFILE
document.getElementById("btnUserInfo").onclick = openuserInfo;
document.getElementById("btnCloseUserInfo").onclick = closeuserInfo;
document.getElementById("btnSaveUserInfo").onclick = saveUserInfo;
document.getElementById("btnCreateItem").onclick = createItem;

const userUsernameField = document.getElementById("txtUsername");
const userEmailField = document.getElementById("txtEmail");
const userAvatarImg = document.getElementById("imgAvatar");
const userAvatarFile = document.getElementById("fileAvatar");

// Refereces & Item Creation

const openCreateItemButton = document.getElementById("btnOpenCreateItem");
const btnCloseCreateItem = document.getElementById("btnCloseCreateItem");
const btnCreateItem = document.getElementById("btnCreateItem");

openCreateItemButton.onclick = async function openCreateItemButton() {
    if (!user) {
        document.getElementById("createItem").style.display = "block";
        console.log("Create Item Opened");
    } else {
        document.getElementById("createItem").style.display = "none";
    }
};

btnCloseCreateItem.onclick = async function btnCloseCreateItem() {
    if (user) {
        document.getElementById("createItem").style.display = "none";
        console.log("itemclosed");
    } else {
        document.getElementById("createItem").style.display = "block";
    }
};

const createItemNameField = document.getElementById("txtCreateItemName");
const createItemDescriptionField = document.getElementById(
    "txtCreateItemDescription"
);
const createItemPriceField = document.getElementById("numCreateItemPrice");
const createItemStatusField = document.getElementById("selectCreateItemStatus");
const createItemFile = document.getElementById("fileCreateItemFile");
const createItemForm = document.getElementById("createItem");
const SaveCreateItem = document.getElementById("btnCreateItem");```

This is my html

<!DOCTYPE html>
<html>
<!-- HEADER STARTS HERE -->

<head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0, shrink-to-fit=no" />

    <!-- Favicons -->
    <link rel="icon" type="image/png" href="icon/favicon-32x32.png" sizes="32x32" />
    <link rel="apple-touch-icon" href="icon/favicon-32x32.png" />

    <meta name="description" content="MrGrandpa doge, Is the ORIGINAL OG of crypto.
    He is a smooth talking r&b singing 🎤 playboy,
    who believes that bitcoin is the most secure investment in the crypto universe,
    don't get him wrong he's a strong believer of doge coin as well." />
    <meta name="keywords" content="MrGrandPaDoge #MRBTC" />
    <meta name="Developer" content="Isaiah Fadakinte" />
    <meta name="Owner" content="Joey Duque" />
    <title>
        MrGrandpadoge NFT Marketplace | No 1 first Multi Network MarketPlace
    </title>

    <script src="https://cdn.jsdelivr.net/npm/web3@latest/dist/web3.min.js"></script>
    <script src="https://npmcdn.com/moralis@latest/dist/moralis.js"></script>
</head>
<!-- HEADER STOPS HERE -->

<!-- BODY STARTS HERE -->

<body>
    <h1>MrGrandPaDoge NFT Marketplace</h1>

    <button id="btnConnect">Connect wallet</button>
    <button id="btnUserInfo">Profile</button>
    <button id="btnOpenCreateItem">Create</button>

    <! -- adding the UserInfo details like Email & username -->

    <div id="userInfo">
        <h4>User Profile</h4>
        <input type="text" id="txtUsername" required placeholder="Enter username" />
        <input type="text" id="txtEmail" placeholder="Enter email" />
        <small>Optional</small>

        <! -- adding the avatar file -->

        <img width="100" height="100" src="" id="imgAvatar" alt="" />
        <label for="fileAvatar">Select Avatar</label>
        <input type="file" id="fileAvatar" />

        <! -- NAV BAR -- >
        <button id="btnLogout">LogOut</button>
        <button id="btnCloseUserInfo">Close</button>
        <button id="btnSaveUserInfo">Save</button>
    </div>

    <! -- CREATE ITEM FIELD -->
    <div id="createItem">
        <h4>Create Item</h4>
        <input type="text" id="txtCreateItemName" required placeholder="Enter name" />
        <textarea id="txtCreateItemDescription" cols="40" rows="8" placeholder="Enter Description"></textarea>
        <input type="number" min="1" step="1" id="numCreateItemPrice" placeholder="Enter Price" required />

        <label for="selectCreateItemStatus">Status</label>
        <select id="selectCreateItemStatus">
        <option value="0">Not For Sale</option>
        <option value="1">Instant Buy</option>
        <option value="2">Accept Offers</option>
      </select>

        <label for="fileCreateItemFile">Select File</label>
        <input type="file" id="fileCreateItemFile" />
        <button id="btnCloseCreateItem">Close</button>
        <button id="btnCreateItem">Create!</button>
    </div>

    <script src="js/main.js"></script>
    <script src="js/abi.js"></script>
</body>
<! --BODY ENDS HERE -->

</html>

you can take a look at the below code i’ve sent, i can’t find the solution to the error, because i have read through the line but i am still in the dark

can you point me to the line that give that error?

This line of code bro