4
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

OpalでUserScriptを書く #opal #userscript

Last updated at Posted at 2015-07-09

OpalはRubyと互換性のある文法を持ったAltJSです。AltJSということは、JavaScriptでできることは基本的にできるということなので、当然ながらUserScriptの作成もできます。

というわけで、UserScriptを作ってみました( https://github.com/cielavenir/ctouch/blob/master/qiita_ciel_tools/qiita_source.user.js をOpalに移植しました )。このコードを実行すると、有効なUserScriptが生成されます。

userscript.rb
# !/usr/bin/ruby
# coding:utf-8

COMMENT=%Q`
// ==UserScript==
// @name        Qiita Source (Opal)
// @namespace   com.cielavenir
// @description Show link to Qiita Markdown source.
// @include     http://qiita.com/*/items/*
// @include     http://qiita.com/*/private/*
// @version     0.0.0.1
// ==/UserScript==
`.lstrip

IO.popen('opal -c','r+b'){|io|
	io.puts DATA.read
	io.close_write
	puts COMMENT
	puts io.read
}

__END__
require 'native'
->{
	doc=Native(`document`)
	ul=doc.getElementsByClassName('itemsShowHeaderTitle_status')[0]
	return if !ul
	li=doc.createElement('li')
	a=doc.createElement('a')
	Native(a).href=Native(`location`).href.split('#')[0]+'.md'
	Native(a).textContent='Markdownを表示する'
	Native(li).appendChild(a)
	Native(ul).appendChild(li)
}.()

__END__以下がOpalのコードになっています。これをopal -cに読ませて、その出力をCOMMENTと結合する形です。COMMENTはUserScriptのマジックコメントを普通に書くことができます(%Q``としましたが、COMMENTにバッククオート入れる方は居ませんよね…?)。

まず、JavaScriptと通信するのを容易にするためにnativeモジュールをrequireし、コード全体を->{...}.()で囲みます。これはJavaScriptでコードを(function(){..})()で囲うのと同じ利点があります。
次に、Native(`document`)でdocumentオブジェクトを拾います。ここで受ける変数名をdocumentにするとグローバルのdocumentオブジェクトが潰れるようなので注意して下さい。
最後に、docを使って要素を生成し、JavaScriptのメソッドやセッタを変数をNativeでくくって呼び出せば完成です。

4
4
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?