例としてこういうボタンを作ってみる
クリックするとアラートが表示されます
このボタンを作るために
HTMLとCSSとJavaScriptをファイル毎に分けるとこのように書けます
- HTMLファイルにボタンを置く
- CSSファイルにスタイルを書く
- JSファイルにスクリプトを書く
これをGoogle Apps Scriptではすべて.htmlにして以下のようなファイルを作ります
ファイル名は任意
- HTMLファイル → index.html
- CSSファイル → style.html
- JSファイル → script.html
そしてindex.html の中で style.html と script.html を以下のように読み込みます
<?!= include('style'); ?>
<?!= include('script'); ?>
<?!= ?> は Google Apps Scriptでは Force-printing scriptlets と 呼ばれています
コード.gsを以下のように書くと Scriptlets を使えるようになります
コード.gs
function doGet() { return HtmlService.createTemplateFromFile('index').evaluate(); } function include(filename) { return HtmlService.createHtmlOutputFromFile(filename).getContent(); } |
意訳この機能がやること 指定したHTMLファイルを表示してScriptlets(<? ?><?= ?><?!= ?>)を使えるようにする この機能がやること 渡されたHTMLファイルの中身を返す |
index.html
<!DOCTYPE html> <html> <head> <?!= include('style'); ?> </head> <body> <button type="button" id="bt" class="bt">アラートを出す</button> <?!= include('script'); ?> </body> </html> |
意訳これはHTML5文書です styleを読み込む ボタンを置く scriptを読み込む |
style.html<style> .bt { color: gray; font-size: 12px; padding: 5px; background-color: whitesmoke; border: 2px solid silver; border-radius: 5px; } </style> | 意訳ここからスタイルです 文字色はgray フォントサイズは12px 内側の余白は5px 背景色はwhitesmoke 枠線は幅2pxで1本線で色はsilver 角丸は5px |
script.html<script> document.getElementById("bt").onclick = bt_clicked; function bt_clicked(){ alert("ボタンがクリックされました") } </script> | 意訳ここからスクリプトです id が bt の要素がクリックされたら bt_clicked を実行する この機能がやること アラートにメッセージを表示する |
ファイルを分けずに書く場合
index.html の中に style も script も書くと以下のようになります
コード.gs
function doGet() { return HtmlService.createHtmlOutputFromFile('index'); } |
index.html<!DOCTYPE html> <html> <head> <style> .bt { color: gray; font-size: 12px; padding: 5px; background-color: whitesmoke; border: 2px solid silver; border-radius: 5px; } </style> </head> <body> <button type="button" id="bt" class="bt">アラートを出す</button> <script> document.getElementById("bt").onclick = bt_clicked; function bt_clicked() { alert("ボタンがクリックされました") } </script> </body> </html> |
補足
Scriptletsについて調べたこと
- .gs側に書くサーバ側のコードを.html側に記述できる
- google.script.runとは異なりページが読み込まれた後に再度実行できない
Scriptlets には3つの使い方があるようです
1. Standard scriptlets
- <? var value = "hello" ?>
- コードを実行するが画面には結果を表示させない
2. Printing scriptlets
- <?= value ?>
- HTMLやJavaScriptにエスケープ文字を追加して画面に表示する
- クロスサイトスクリプティング(XSS)攻撃から保護するためのエスケープ文字を追加する
3. Force-printing scriptlets
- <?!= value ?>
- HTMLやJavaScriptをそのまま画面に表示する
- クロスサイトスクリプティング(XSS)攻撃から保護するためのエスケープ文字を追加しない
- 通常は Printing scriptlets を使う
参考
HTML Service: Templated HTML / Scriptlets
https://developers.google.com/apps-script/guides/html/templates
Separate HTML, CSS, and JavaScript
https://developers.google.com/apps-script/guides/html/best-practices
to protect against cross-site scripting (XSS) attacks
https://developers.google.com/closure/templates/docs/security
Class google.script.run (Client-side API)
https://developers.google.com/apps-script/guides/html/reference/run