swiftwasm / JavaScriptKit

Swift framework to interact with JavaScript through WebAssembly.

Home Page:https://swiftpackageindex.com/swiftwasm/JavaScriptKit/main/documentation/javascriptkit

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

TypeError when trying to implement a JSBridgedClass for WebSocket.send

austintatiousness opened this issue · comments

I've set up a JSBridgeClass for the WebSocket class using the following code, but I get "TypeError: 'send' called on an object that does not implement WebSocket" or "expression unexpectedly raised an error: TypeError: Can only call WebSocket.send on instances of WebSocket: file JavaScriptKit/JSFunction.swift, line"

class WebSocket: JSBridgedClass {
	public class var constructor: JSFunction { JSObject.global.WebSocket.function! }
	
	public convenience init(uri: String) {
		print("trying to connect to: \(uri)")
		self.init(unsafelyWrapping: Self.constructor.new(uri)) //This works, my server connects
	}
	

	public func sendMessage(data: Data) {
		if let string = String(data: data, encoding: .ascii) {
			
			//Tried Importing DOMKit to use Blob
			//let l = BufferSourceOrBlobOrString.string(string)
			//let blob = Blob(blobParts: [l])
			if let function = self.jsObject.send.function {
				function(string)  //TypeError: 'send' called on an object that does not implement interface
				//function(blob.jsObject)
				function("MAYBE THIS WILL WORK?") //TypeError: 'send' called on an object that does not implement interface
			}
		}
	}
}

I would appreciate some direction 😩 . Perhaps I am misunderstanding how to implement JSBridgedClass properly.

The problem here is that let function = self.jsObject.send.function returns an unbound function, meaning that calling it will not properly set the this value on the JS side. Since you’re requiring the jsObject to be an instance of WebSocket, this code should work:

	public func sendMessage(data: Data) {
		if let string = String(data: data, encoding: .ascii) {
			
			//Tried Importing DOMKit to use Blob
			//let blob = Blob(blobParts: [.string(string)])
			jsObject.send(string)
		}
	}

When I change it to

self.jsObject.send!(string)

I get the following error:

Fatal error: 'try!' expression unexpectedly raised an error: InvalidStateError: The object is in an invalid state.: file JavaScriptKit/JSFunction.swift, line 22

After hours of aimlessly trying different code. It dawned on me that I was sending data too soon. The socket wasn't fully open.