Copy and Paste to and from clipboard (DEF-2070)

I need this mainly so users can copy and paste long strings of text to use as secret keys for authentication such as “PTsky0EITXT8agihiKu3FiPZ9pjAmKDjqGVvF4iQ”

2 Likes

Created a ticket: DEF-2070

1 Like

Sorry to drag DEF-2070 out from the depths of the backlog, but just to see if it’s on the horizon? This would be useful to copy and share unique item IDs for a game I’m building.

Have you tried https://github.com/britzl/defold-clipboard ?

3 Likes

Amazing. I was going to have to look for something like that in a few hours.

1 Like

I hadn’t, thanks for the pointer! Works a charm. :partying_face:

@britzl could this work with HTML5?

1 Like

Maybe. It’s another security thing that needs to be circumvented though. It might be doable.

1 Like

That would be awesome!

The code for copying to clipboard is basically this:

But I think the code has to be triggered from a javascript event which complicates things.

1 Like

Defos has a defos.on_click() that lets you run a callback from the onclick JS event.

4 Likes

Apologies, but now I need this again. :slight_smile:

I’m able to capture the click with the very handy defos.on_click(), which should mean a clipboard call is valid. The issue now is that the global clipboard is not available when bundling to HTML5.

Would it be possible to enable the extension on HTML5, to see if this works inside the defos.on_click() event?

You could do something like

local function copy_text()
	local result = html5.run("navigator.clipboard")
	print(result)
	if result == "[object Clipboard]" then
		print("Trying to access clipboard")
		html5.run("clipboard_copy('Defold is cool!')")
	else
		print("Can't access clipboard")
	end
end

function init(self)
	msg.post(".", "acquire_input_focus")
end

function on_input(self, action_id, action)
	if action_id == hash("touch") and action.released then
		print("Trying to copy!")
		defos.on_click(function() 
			copy_text()
		end)
	end
end

Then add to your HTML5 template

	<script type="text/javascript">
	async function clipboard_copy(thing_to_copy) {
	   const result = await navigator.clipboard.writeText(thing_to_copy);
	}
	</script

The game canvas needs focus too so you can detect if it has focus or not and have a thing display saying to click/tap to give focus before letting them click whatever it is you want as the input to put something into their clipboard.

1 Like