Godot Version 4.3
Ok here we go. Due to lack of documentation on JavaScriptBridge, I need some help sharing fetched data from the web to GDScript, to use in-game.
I have a custom HTML shell that has JavaScript in it to call an API and return data. In Godot, I have a button that uses the JavaScriptBridge Singleton to execute said script.
fetchData() is executed and pulls back some dummy data.
How can I used the JavaScriptBridge Singleton to get that stored data and assign it to a GDSccript variable?
I’m guessing has something to do with, but. I don’t know the syntax.
var user = JavaScriptBridge.create_object(" ")
This is the javascript in custom web shell .html page:
function fetchData() {
// Fetch data from the JSONPlaceholder API
fetch('https://jsonplaceholder.typicode.com/todos/1')
.then(response => response.json()) // Parse the JSON response
.then(data => {
console.log('Fetched Data:', data); // Log the data to the console
})
.catch(error => {
console.error('Error fetching data:', error); // Log any errors to the console
});
}
This is the GDScript that gets the document window, and executes the javascript fetchData()
extends Control
# GET DATA FIELD UI
@onready var data_field = $data_field
# GLOBAL WINDOW VARIABLE
var window
# USER ACCOUNT
var user
# Called when the node enters the scene tree for the first time.
func _ready():
# GET THE BROWSER WINDOW
window = JavaScriptBridge.get_interface("window")
func _on_button_pressed():
# UPDATED TEXT FIELD
data_field.text = "Function Executed"
# EXECUTE SCRIPT TO CONNECT WALLET
window.fetchData()
The data returned is
Fetched Data:
{userId: 1, id: 1, title: 'delectus aut autem', completed: false}
completed: false
id: 1
title: "delectus aut autem"
userId: 1
I want to get a least the js “userID” assigned to the GDScript variable “user”.
I’m still trying to figure this out. I created another button that will the script to pull the userID from JavaScript to display in Godot UI Label Field - however, it displays
func _on_display_pressed():
account = window.PlayerID
label.text = str(account)
You can see in the console, I can pull up PlayerID and it will have a value of 1
How do I get that PlayerID value of 1 to display in Godot UI?