[HTML5] Javascript return data

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By andy_

Hi all, The code below opens a file via javascript and save the content in a variable. Since i am new to godot, i have no idea how to get the data in to gdscript for processing. Can anyone help?

Thanks

extends Control

func _on_Button_pressed():
var content = JavaScript.eval("""
	var input = document.createElement('input');
	input.type = 'file';
	input.onchange = e => { 
		var file = e.target.files[0]; 
		var reader = new FileReader();
		reader.readAsText(file,'UTF-8');
		reader.onload = readerEvent => {
		var filecontent = readerEvent.target.result; // this is the content!
		}
	}
	input.click();
""")

i recommend watching this video: godot-javascript-bridge. it explains all you need for working with js, including uploads to godot, helped me alot.

trisolaran | 2022-02-23 15:04

:bust_in_silhouette: Reply From: mrimvo

Hey Andy, I got the same problem and based on your work came up with this.

I want to read an image though, but the principle should be the same:


JavaScript.eval("""
	var input = document.createElement('input');
	input.type = 'file';
	input.onchange = e => { 
		var file = e.target.files[0]; 
		var reader = new FileReader();
		reader.readAsText(file,'UTF-8');
		reader.onload = readerEvent => {
			var filecontent = readerEvent.target.result; // this is the content!
			var img = document.createElement('img');
			img.id = "output";
			img.data = filecontent;
			document.body.appendChild(img);
		}
	}
	input.click();
""")

    # wait for the result to appear
while true:
	yield(get_tree().create_timer(1), "timeout")
	var result = JavaScript.eval("""(function () {
		var output = document.getElementById("output")
		if (output!== null) {
			console.log("output found")
			return output.data
		}
		return null
	})() """)
	print (result)