Elm open url in a new tab

Viewed 749

I am trying to learn Elm and trying to figure how to open a url in a new tab instead of the same page.

The following piece of code opens the URL in same page:

Browser.Navigation.load (url)

what do I need to replace this with so this URL opens in a new tab?

2 Answers

You should be able to easily do this with ports.

port module Main exposing (main)

port newTab : String -> Cmd msg

and in JS

app.ports.newTab.subscribe( url => window.open(url, '_blank'));

[2021-02-22] edit:

The above solution assumes that the programmer wants to open an url programmatically (from the update function) and that Html.target_ "_blank" was not an option.

An Elm app doesn’t manage your browser tabs, just the one tab in which it is currently running (neither does a JS app, by the way!).

So the Browser.Navigation API is of no use here, you must simply use a plain HTML a with target="_blank", as @viam0zah commented:

Html.a [ Html.Attributes.target "_blank"] [ Html.text "Open in a new tab" ]
Related