1

I am trying to use Yew in an SPA alongside some external Javascript. I'm looking for the right way to enable the external Javascript code to change the current route in my Yew application without causing a network reload.

I have experimented with setting window.location.href from the console but that reloads the Yew app (as expected) and this is not what I want in this SPA.

I believe I need a small bit of Javascript to deliver a message to my Yew app and have my Yew app use the Navigation API to call navigator.push() as appropriate.

I've used Elm a little bit before this is my first Yew application. I searched around and looked at the source to various applications to find an idiomatic way in Yew to do to something like what Elm enables with ports. In Elm I'd declare a port, have my Javascript send a message to it and use a subscription to trigger an update to Elm's Browser.Navigation module.

While looking around I did come across an article and chat application which relays input from a web socket to Yew via a Yew agent and a web worker. It is very clever but seems a little much for what I'm trying to do.

So my questions are:

  1. What is the idiomatic way to change the Yew router route from external Javascript?

  2. More generally is there anything in the Yew ecosystem to allow a Yew SPA to communicate with external Javascript in the way Elm ports do? Or is there a simpler approach? From what I've read I think I might be able to create a callback in Yew and register it somewhere the external JS can call with wasm-bindgen.

jq170727
  • 13,159
  • 3
  • 46
  • 56
  • Seems [@athan-clark](https://stackoverflow.com/users/1465116/athan-clark) had a [similar question](https://stackoverflow.com/questions/72958259/using-a-yew-callback-as-a-wasm-bindgen-closure) a few months back. – jq170727 Jan 22 '23 at 20:19
  • Looks like [this gist](https://gist.github.com/craftyc0der/1e71964cc3e85d533f0f70985c22a74a#setup-wasm-bindgen-for-the-javascript-code) and [blog post](https://craftycoder.com/blog/firebase-yew/) from [craftyc0der](https://gist.github.com/craftyc0der) may provide one way of setting up a JS -> Yew callback. – jq170727 Jan 22 '23 at 20:46

1 Answers1

1

I found a way to do what I need by having

  • Yew render a div within a BrowserRouter
  • Yew add an EventListener on the div which changes the route when it sees a CustomEvent
  • A Javascript function dispatch a CustomEvent to the div when called

Example is here: https://github.com/jq170727/change_yew_route_from_js

This works but I'm sure it could be improved.
Suggestions or coding advice always appreciated .

jq170727
  • 13,159
  • 3
  • 46
  • 56