Jump to content

Need help on executeBrowserJavascript


Recommended Posts

Hello guys, im working on script that sends information from Lua to html table but i dont know why it doesnt work.

addEvent("updateLeaderboard", true)
addEventHandler("updateLeaderboard", root, function(leaderboardData)
    local leaderboardJSON = toJSON(leaderboardData)
    local escapedJSON = string.gsub(leaderboardJSON, "'", "\\'")
    outputChatBox("Leaderboard JSON: " .. escapedJSON)

    if isElement(theBrowser) then
        local script = string.format("populateLeaderboard('%s');", escapedJSON)
        executeBrowserJavascript(theBrowser, script)
    end
end)

bindKey("b", "down",
    function()
        local leaderboardData = {
            pvpKills = {
                ["player1"] = { pvpKills = 10, npcKills = 5, stuntPoints = 200, mostWanted = 2 },
                ["player2"] = { pvpKills = 8, npcKills = 4, stuntPoints = 150, mostWanted = 1 }
            }
        }
        
        local testJSON = toJSON(leaderboardData)
        local escapedTestJSON = string.gsub(testJSON, "'", "\\'")
        iprint(escapedTestJSON)
        
        if isElement(initBrowser) then
            local script = string.format("populateLeaderboard('%s');", escapedTestJSON)
            outputChatBox("SCRIPT : " ..script)
            --iprint("Working")
            executeBrowserJavascript(theBrowser, script)
        end
    end)        

i have shared my testing part too

this is javascript side

document.addEventListener("DOMContentLoaded", function () {
    const leaderboardBody = document.getElementById('leaderboard-body');
    window.populateLeaderboard = function (leaderboardDataJSON) {
        console.log("populateLeaderboard called with data:", leaderboardDataJSON);

        try {
            const leaderboardStats = JSON.parse(leaderboardDataJSON);
            console.log("Parsed leaderboard data:", leaderboardStats);

            leaderboardBody.innerHTML = ''; 
            for (const playerName in leaderboardStats.pvpKills) {
                const playerData = leaderboardStats.pvpKills[playerName];
                const row = document.createElement('tr');
                row.innerHTML = `
                    <td>${playerName}</td>
                    <td>${playerData.pvpKills}</td>
                    <td>${playerData.npcKills}</td>
                    <td>${playerData.stuntPoints}</td>
                    <td>${playerData.mostWanted}</td>
                `;
                leaderboardBody.appendChild(row);
            }
        } catch (error) {
            console.error("Error parsing leaderboard data: ", error);
        }
    };
});

 

Link to comment

There are some syntax errors in the lua script, such as using se instead of if and fim instead of end. This needs to be fixed.

The

populateLeaderboard

function will only be called on the JavaScript side when the Lua event is fired correctly. Make sure the updateLeaderboard event is being fired correctly and the Browser is available and initialized at the time you execute the JavaScript.

Additionally, the JSON you are generating appears to be escaping the single quote characters (') with \\', which is common, but make sure the JSON being passed to JavaScript is valid. If there are escaping or formatting errors, JavaScript may fail to parse the data.

addEvent("updateLeaderboard", true)
addEventHandler("updateLeaderboard", root, function(leaderboardData)
    local leaderboardJSON = toJSON(leaderboardData)
    local escapedJSON = string.gsub(leaderboardJSON, "'", "\\'")
    outputChatBox("JSON do placar: " .. escapedJSON)

    if isElement(theBrowser) then
        local script = string.format("populateLeaderboard('%s');", escapedJSON)
        executeBrowserJavascript(theBrowser, script)
    end
end)

bindKey("b", "down", function()
    local leaderboardData = {
        pvpKills = {
            ["player1"] = {pvpKills = 10, npcKills = 5, stuntPoints = 200, mostWanted = 2},
            ["player2"] = {pvpKills = 8, npcKills = 4, stuntPoints = 150, mostWanted = 1}
        }
    }

    local testJSON = toJSON(leaderboardData)
    local escapedTestJSON = string.gsub(testJSON, "'", "\\'")
    iprint(escapedTestJSON)

    if isElement(theBrowser) then
        local script = string.format("populateLeaderboard('%s');", escapedTestJSON)
        outputChatBox("SCRIPT: " .. script)
        executeBrowserJavascript(theBrowser, script)
    end
end)

In this version, typing and syntax errors are corrected.

(theBrowser): Make sure theBrowser is properly initialized, make sure the browser is receiving and processing the data correctly. The console.log on the JavaScript side is essential for debugging this. Open the browser's developer tools to check the console output, you already have a try/catch. If there is a problem parsing the data on the browser side, this should show up in the console

 

theBrowser = createBrowser(800, 600, false, false)
addEventHandler("onClientBrowserCreated", theBrowser, function()
    loadBrowserURL(theBrowser, "address")
end)

Pay more attention when coding!

Link to comment

everything works correctly without errors and even no errors on console log

this event "updateLeaderboard" called from server side so i can transfer data from server side to html list 

i dont see any changes done to my actual code that you did

Link to comment

The event is being fired, but the client function is not processing the data correctly, the browser is not properly initialized, or the JavaScript is not executing as expected.
The JSON being passed may be modified or misinterpreted between Lua and the browser.

triggerClientEvent(player, "updateLeaderboard", player, leaderboardData)

check if the event is actually being fired and the leaderboardData is sent, Here, player must be the correct player who will receive the data. Use root if you want to send it to all players.

On the JavaScript side, add more debugging to see if data is coming through, also ensure that the updateLeaderboard event is being captured and that JavaScript is being executed. Add outputChatBox and console.log to monitor the flow

Link to comment
function updateLeaderboard()
     local leaderboardData = {
        pvpKills = {
            ["player1"] = { pvpKills = 10, npcKills = 5, stuntPoints = 200, mostWanted = 2 },
            ["player2"] = { pvpKills = 8, npcKills = 4, stuntPoints = 150, mostWanted = 1 }
        }
    }
    local leaderboardJSON = toJSON(leaderboardData)
    triggerClientEvent("updateLeaderboard", resourceRoot, leaderboardJSON)
    
end

this is what i have done on server side, i have added that table later to test faster. everything was working perfectly since it was displaying on dxDrawText but i wanted to go more further with this script and changed it to html page. so i can have better looking but found out that no errors and have changed everything possible to make it work even tried iprint everything and it already sends the data but it doesnt display.

i have tested the javascript function on console and it works with no problem

my main issue here is that im not having errors to catch and fix. so i thought its 100% sure the problem on javascript but no errors as well

Link to comment

So that means there is something wrong with your source but you can't find where it is?

The last thing I think might be wrong is your meta.xml,

<meta>
    <info author="your name" version="1.0" name="hshshshshsh"/>

    <!-- you may be using "script src=" instead of "file src=" --->
    <file src="leaderboard.html" download="true"/>
</meta>

If it's not any of those things I mentioned, I have no idea what the problem is.

Link to comment
Just now, Laxante101 said:

So that means there is something wrong with your source but you can't find where it is?

The last thing I think might be wrong is your meta.xml,

<meta>
    <info author="your name" version="1.0" name="hshshshshsh"/>

    <!-- you may be using "script src=" instead of "file src=" --->
    <file src="leaderboard.html" download="true"/>
</meta>

If it's not any of those things I mentioned, I have no idea what the problem is.

html page works well, it can be displayed when i press on F5, so dont think that problem in this case

Link to comment

i have some data like counts how many kills players got and will display them on html page, its a leaderboard page and when i press F5 to see the information for each player, the list is empty and not getting errors

Link to comment

Add more debug logging to your Lua and JavaScript code to trace the data flow and identify where the problem occurs, and also
Check that the "updateLeaderboard" event is being fired correctly and that "leaderboardData" is being sent to the client.

Link to comment
Posted (edited)

this is the output of the result

leaderboard data:

[ "[ { \"stuntPoints\": [ ], \"mostWanted\": [ ], \"pvpKills\": { \"Snow-Man\": { \"stuntPoints\": 0, \"mostWanted\": 0, \"pvpKills\": 0, \"npcKills\": 1 } }, \"npcKills\": [ ] } ]" ]

 

Edited by Snow-Man2
Link to comment
  • Moderators
3 hours ago, Snow-Man2 said:

leaderboard data:

It looks like you got some unparsed JSON in your JSON result.

console.log(typeof(leaderboardStats))

// If type is object:
const result = JSON.parse(leaderboardStats[0])

// or if the type is a string:
const result = JSON.parse(leaderboardStats)

 

To make things a bit easier, use back-ticks so you do not have to escape your own JSON:

local script = string.format("populateLeaderboard(`%s`);", escapedTestJSON)

 

 

Link to comment
Posted (edited)

when i did that i gave me the result as an object and then i have did what you told me to use this 

const result = JSON.parse(leaderboardStats[0])

then i got this error 

index.html:89 Error parsing leaderboard data:  SyntaxError: Unexpected end of JSON input
    at JSON.parse (<anonymous>)
    at window.populateLeaderboard (index.html:71:43)
    at <anonymous>:1:1

 

Edited by Snow-Man2
Link to comment
  • Moderators
10 minutes ago, Snow-Man2 said:

then i got this error 

 

And if you do not modify the JSON? (and use backticks)

local testJSON = toJSON(leaderboardData)

if isElement(initBrowser) then
	local script = string.format("populateLeaderboard(`%s`);", testJSON)
	outputChatBox("SCRIPT : " ..script)
	executeBrowserJavascript(theBrowser, script)
end

 

const leaderboardStats = JSON.parse(leaderboardDataJSON);
console.log("Parsed leaderboard data:", leaderboardStats);

 

Link to comment
Posted (edited)

i have realized that im using toJSON on server side and i have got rid of it

now im not getting any errors just output on browser this

type:  string
index.html:73 Parsed leaderboard data: [{…}]0: mostWanted: []npcKills: []pvpKills: Snow-Man: mostWanted: 0npcKills: 1pvpKills: 0stuntPoints: 0[[Prototype]]: Object[[Prototype]]: ObjectstuntPoints: Array(0)length: 0[[Prototype]]: Array(0)[[Prototype]]: Objectlength: 1[[Prototype]]: Array(0)

its the output of 

 console.log("type: ", typeof(leaderboardDataJSON))
and 
console.log("Parsed leaderboard data:", leaderboardStats);
so no errors anymore but im not seeing these data showed up on html leaderboard
Edited by Snow-Man2
Link to comment
  • Moderators
2 hours ago, Snow-Man2 said:

console.log("Parsed leaderboard data:", leaderboardStats);

And what does this output?

 console.log("Parsed leaderboard data:", leaderboardStats, typeof(leaderboardStats)); 

 

Link to comment
Posted (edited)

thank you so much, its fixed now, when i did that line it returned object to me, so i used this 

leaderboardStats[0] and now it shows data on leaderboard

but why each time i try to close the browser my game crashes even other people got the same problem like me, the game crashes for all of us

Edited by Snow-Man2
Link to comment
  • Moderators
12 minutes ago, Snow-Man2 said:

but why each time i try to close the browser my game crashes even other people got the same problem like me, the game crashes for all of us

How do you close the browser? (as in code)

Link to comment

okay thank you, i will do that

it makes the same issue, its not solved yet

this is what i have done 

my game crashes each time i try to close the browser

bindKey("F5", "down", function()
    if isTimer(spamTimer) then
        return false
    end
    if not isElement(theBrowser) then
        local initBrowser = guiCreateBrowser(0, 0, sX, sY, true, true, false)
        theBrowser = guiGetBrowser(initBrowser)
        addEventHandler("onClientBrowserCreated", theBrowser, loadTheBrowser)
    else
        setBrowserRenderingPaused (theBrowser, true)
        destroyElement(theBrowser)
        theBrowser = nil
    end
	spamTimer = setTimer(function() end, 1000, 1)
end)

 

Edited by Snow-Man2
Link to comment

você pode tentar usar setBrowserRenderingPaused(theBrowser, true) para pausar a renderização do navegador antes de destruí-lo. Isso pode ajudar a resolver o problema.

 

Edit: I didn't see that they had mentioned that, :(

Edited by Laxante101
Link to comment

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...