Skip to content

TypeError when trying to implement a JSBridgedClass for WebSocket.send #120

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
austintatiousness opened this issue Feb 22, 2021 · 3 comments

Comments

@austintatiousness
Copy link

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.

@j-f1
Copy link
Member

j-f1 commented Feb 22, 2021

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)
		}
	}

@austintatiousness
Copy link
Author

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

@austintatiousness
Copy link
Author

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants