Y's note

Web技術・プロダクトマネジメント・そして経営について

本ブログの更新を停止しており、今後は下記Noteに記載していきます。
https://note.com/yutakikuchi/

iPhoneのwindow.getSelection()について

値の取得

window.getSelection(document.getSelection)は画面のドラッグにより選択した文字列を読み取るjavascriptの関数です。
以前はsafariなどで利用できなかったようですが、現在はほとんどのブラウザで読み取ることが可能です。
(safari/firefox/chrome/operaでは動作を確認しています。2011/2/15日現在)
iphoneでwindow.getSelectionを利用するときに少しハマったので、メモしておきます。

browser-javascript

HTMLに仕込んだjavascriptのwindow.getSelection()はiphoneでも動作します。
HTMLを読み込んだ時点でjavascriptが正しく設定されていると値が取得できるようです。
以下は選択肢た文字列をgoogle検索結果に自動的に飛ばす処理を書いています。

<!DOCTYPE html>
<html><head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<meta http-equiv="Pragma" content="no-cache">
<meta http-equiv="Cache-Control" content="no-cache">
<title>get Selection Test</title>
<script>
var drag = false;
var getText = function() {
    if( drag === true  ) {
        window.open( 'http://www.google.com?q=' + encodeURI( window.getSelection() ) );
    }
    drag = false;
}

var setDragStatus = function() {
    drag = true;
}

document.addEventListener( 'touchend', getText, false );
document.addEventListener( 'touchstart', setDragStatus, false );
</script>
</head>
<body>
選択文字列 iPhone テスト<br> 
選択文字列 iPhone テスト<br> 
選択文字列 iPhone テスト<br> 
<br><br>
選択文字列 iPhone テスト<br> 
</body>
</html>

bookmarklet-javascript

bookmarkletの場合は注意が必要です。※PCのbrowserでは以下のコードが動作しても、iphone上では動作しません。
作業手順は文字列選択→bookmarklet起動という流れです。

javascript:void((function(){alert(window.getSelection());})());

上の件を調査してみると、bookmarkletとしてwindow.getSelection()を使うことはできないようです。bugとして報告されています。
http://openradar.appspot.com/7013257

解決方法

以下単純ですが、iPhone対策としてのbookmarklet-javascriptを記述します。適用できないケースも有ると思うので、そこに関してはご勘弁を。
※上と作業手順が変わります。bookmarklet起動→文字列選択となります。
変更点は2点です。

  1. bookmarkletではwindow.getSelectionを呼び出さない。
  2. bookmarkletではtouchendイベントにてwindow.getSelection()を取得するようなコードをHTMLに仕込む。

変更後のサンプルです。hoge.jsの箇所は適当に読み込みたいjavascriptファイルパスに変えてください。

bookmarklet
javascript:void((function(){s=document.createElement('script');s.setAttribute('src','hoge.js');document.body.appendChild(s);})());
bookmarkletから読み込まれるjavascript
var drag = false;
var getText = function() {
    if( drag === true  ) {
        window.open( 'http://www.google.com?q=' + encodeURI( window.getSelection() ) );
        //alert( window.getSelection() );
    }
    drag = false;
}

var setDragStatus = function() {
    drag = true;
}
document.addEventListener( 'mouseup', getText, false );
document.addEventListener( 'mousedown', setDragStatus, false );
document.addEventListener( 'touchend', getText, false );
document.addEventListener( 'touchstart', setDragStatus, false );

このように変更するとiphoneでもbookmarklet起動で選択文字列が取得できます。
意外とiPhoneの画面ドラッグだけでGoogle検索に飛ばすのはUI的に楽かもしれないですね。