6
7

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.

JXAでMacのSafari・Chrome内でJavaScriptを実行する時は関数をtoString()するといいかも

Last updated at Posted at 2016-02-25

SafariとChromeの操作方法の違いは以下を参照
JXAでSafari, Chrome, Firefoxを操作する際の違い

サンプル

ブラウザのダイアログに「hello.」と表示して「goodbye.」という文字列を得る
最後に評価された式の結果が戻り値になる

Safariの場合
SCRIPT = "alert('hello.'); 'goodbye.'"

app = Application("Safari")
tab = app.windows[0].tabs[0]

app.doJavaScript(SCRIPT, {in: tab}) // "goodbye."
Chromeの場合
SCRIPT = "alert('hello.'); 'goodbye.'"

app = Application("Chrome")
tab = app.windows[0].tabs[0]

tab.execute({javascript: SCRIPT}) // "goodbye."
// app.execute(tab, {javascript: SCRIPT})を省略した書き方

エラー出た場合はnullが返る

で、文字列で渡さなきゃいけないから複雑なスクリプトを実行したいときに不便
エディタのシンタックスハイライトも補完も効かない
複数行書くのもエスケープもめんどい

そんな時は普通に関数として書いて.toString()し、即時実行させればいい

chrome_sample.js
func = function(){
  var message = "ぃぇぁ";
  alert(message);
  return message;
}

func_str = "(" + func.toString() + ")()"

app = Application("Chrome")
tab = app.windows[0].tabs[0]
tab.execute({javascript: func_str})

おまけ

ヒアドキュメントっぽいやつ

here_document.js
var text = (function(){/*
あああ
いいい
ううう
*/}).toString().split(/\r?\n/).slice(1, -1).join("\n")
6
7
0

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
6
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?