Skip to content Skip to sidebar Skip to footer

Haskell Webviewhs GetElementById From A Webpage

Still most potential for a GUI to Haskell for me, but missing some essential info in the examples, being a noob Haskeller. Assuming one of the examples: {- webviewhs (C) 2018

Solution 1:

As the github page shows, you can receive data from JS with a callback, and execute arbitrary JS in the window from Haskell. This is enough to do any sort of communication you might want, here's an example that that executes some Haskell on a button press and then shows the result in the webpage:

{-# LANGUAGE OverloadedStrings, QuasiQuotes #-}
module Main where

import System.Directory(getCurrentDirectory)
import Text.Printf
import Control.Monad(void)
import Language.Javascript.JMacro
import qualified Graphics.UI.Webviewhs as WHS
import qualified Data.Text as T

windowCallback window = do
  return True

handleJSRequest window request = void . WHS.runJavaScript window $ [jmacro|
  show_response `(printf "'Got response: %s'" request :: String)`
  |]

main :: IO ()
main = void $ do
  dir <- getCurrentDirectory
  WHS.withWindowLoop
    WHS.WindowParams
      { WHS.windowParamsTitle = "Test"
      , WHS.windowParamsUri = T.pack $ printf "file://%s/example.html" dir
      , WHS.windowParamsWidth = 800
      , WHS.windowParamsHeight = 600
      , WHS.windowParamsResizable = True
      , WHS.windowParamsDebuggable = True
      }
    handleJSRequest
    windowCallback
<html>
  <head>
    <title>Example</title>
    <meta charset="utf-8">
  </head>
  <body>
    <script type="text/javascript">
      function show_response(response) {
        document.getElementById('response').innerHTML = response;
      }
      function submit() {
        var value = document.getElementById('textbox').value;
        window.external.invoke(value)
      }
    </script>
    <input type="text" id="textbox"/>
    <input value="say hello" type="button" onclick="submit()"/>
    <p id="response"></p>
  </body>
</html>

You should note though that the haskell webview library has only 2 commits, the last of which was more than 7 months ago, so it's not exactly being actively developed at the moment.


Post a Comment for "Haskell Webviewhs GetElementById From A Webpage"