Using native JavaScript objects from Opal

Question: can I call JS functions from Opal?
Answer: totally!

Opal standard lib (stdlib) includes a native module, let’s see how it works and wrap window:

require 'native'

window = Native(`window`) # equivalent to`window`)

Now what if we want to access one of its properties?

window[:location][:href]                         # => ""
window[:location][:href] = "" # will bring you to

And what about methods?

window.alert('hey there!')

So let’s do something more interesting:

class << window
  # A cross-browser window close method (works in IE!)
  def close!
      return ('', '_self', '') && #@native.close()) ||
             (#@native.opener = null && #@native.close()) ||
             (#@native.opener = '' && #@native.close());

  # let's assign href directly
  def href= url
    self[:location][:href] = url

That’s all for now, bye!


Leave a Reply

Please Login to comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.