LoginSignup
18
16

More than 5 years have passed since last update.

electronのwebview.executeJavaScriptで書くjavascriptを見やすくしてみた

Last updated at Posted at 2015-10-03

electronのwebviewでは、
executeJavaScriptがあり、webview先でjavascriptを走らせることができる。
通常の使い方だと、こんな感じに、文字列を書かざるおえない。

var webview = document.getElementById('mainWebview');

webview.executeJavaScript("alert(\"hogehoge\");");

これだと、以下の問題があって管理しづらい

  • 文字列一色でシンタックスハイライトが効かない
  • ヒアドキュメントのテクニックを使わないかぎり複数行かけない
  • 文字列ゆえにダブルクォートなどが書きづらい

この問題を解決してみた(微妙に苦労したので書いておく)。

こういう形で書けば見やすくなった

var webview = document.getElementById('mainWebview');

webview.executeJavaScript(
  (function(){
    alert("hogehoge");
  }).
  toString().replace(/function\s*\(\)\{/, "").
 replace(/}$/,"").trim()
);

functionオブジェクトは、toStringメソッドがあり、これを呼び出せばコードの内容含めて文字列で出力してくれるようなので、これを用いた。

あとは"function(){"と最後の"}"と余分な空白除去してあげれば、webviewで動くjavascriptコードにはなるという寸法

これで複数行のコードをwebviewで実行させるときでも一安心

18
16
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
18
16