Search code examples
javascriptdomf#websharper

How to interact and set DOM properties with WebSharper?


I often need to interact with my page's DOM, how can I do it via WebSharper?

For instance when I want to redirect my page in just JavaScript I'd run:

window.location = "http://www.google.com/";

How can I access window and set location? how would this look in F#?
Also, how would it work with functions, for instance with IE's:

window.navigate("http://www.google.com/")

Note: If there is a built-in way to redirect via WebSharper I'd love to know it but keep in mind this is just an example.


Solution

  • You can access the window.location property after opening the IntelliFactory.WebSharper.Html5 namespace which provides support for the standard HTML5 APIs. In order to navigate using the location object you can call the assign or replace methods:

    Window.Self.Location.Assign "http://www.google.com/"
    

    A live demo is available here.

    For vendor specific functions you can inline the JavaScript and use it as if it was built into WebSharper:

    [<Inline "window.navigate($uri)">]
    let ieNavigate uri = X<unit>