Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I create a js/Notification in ClojureScript that can focus on the window?

I want to create a (chrome) Notification with text, and I can click on the notification to be taken to the page that issued the notification. Here's the closest I've gotten, and notice it's very much non-idiomatic. I had to use js* (js star) which, I can't find docs for, but it just executes a string of javascript.

(js* "  var notification = new Notification('Here is the title', {
    icon: 'http://path.to/my/icon.png',
    body: 'Some body text',
  });

  notification.onclick = function () {
    console.log('hi there');
    this.close();
    window.focus();
  };")

Notice, the log works, the close works, but the window.focus() does not. If you copy and past the js portion of this code into your browser's console, it does work.

I think the correct answer should look more like the following, but the onclick doesn't work at all, for any function:

(new js/Notification "Here is the title"
             (clj->js {:body "(click to vist page)"
                       :onclick #(.focus js/window)}))

EDIT: if you type in the following (say, in figwheel), js/window definitely has a focus param. Obvious, but I just checked, but it doesn't work when called with (.focus js/window):

(.keys js/Object js/window)

This doesn't even work to focus:

(js* "window.focus()")

And I can't seem to find any keys attached to js/Notification to get onclick working:

(.keys js/Object (new js/Notification "hi" (clj->js {:body "body text"})))

I must be doing something wrong, but what?

like image 476
Josh.F Avatar asked Nov 26 '25 04:11

Josh.F


1 Answers

Here is a "straight port" of your original JavaScript code:

(let [title "Here is the title"
      js-opts (js-obj "icon" "http://path.to/my/icon.png"
                      "body" "Some body text")
      js-notification (js/Notification. title js-opts)]
  (aset js-notification "onclick"
    (fn []
      (this-as js-this
        (.log js/console "hi there")
        (.close js-this)
        (.focus js/window)))))

Notice I prefixed JavaScript references with js-, which is a common convention when dealing with JavaScript interop in ClojureScript.

like image 177
Chris Oakman Avatar answered Nov 28 '25 00:11

Chris Oakman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!