この記事について
| 環境 | javascript + jQuery(iframe) |
|---|---|
| 目的 | インラインフレーム内で選択したテキストを取得する |
| 結果 | contentDocument.getSelection() で取得できた。androidはtouchendのタイミングで保存 |
つまずきポイント要約
- androidはボタンタップで選択が解除されるので、touchend時にグローバル変数へ保存しておく
選択したテキストを取得して確認するために、アラートで表示するスクリプトをつくった。
test.js
//ボタンが押されたら
$('#test_bt').on('click', function () {
var selObj = document.getElementById('iframe').contentDocument.getSelection();
//もしくはこちら
//var selObj = document.getElementById('iframe').contentWindow.getSelection();
alert("選択した文字列: " + selObj); //アラートで表示
});
test.html
<div class="ifrm-container">
<iframe src="iframe_test.html"></iframe>
</div>
<div>
<input type="button" value="ボタン" id="test_bt">
</div>
あらかじめテキストを選択しておいて、ボタンが押されたら選択されたテキストがはいったアラートを表示する方法をとったのだが、android だとボタンを押すとテキストの選択が解除される。「選択解除」 → 「選択テキストを取得してアラートを表示」の順番になるのでうまく取得できない。
<<追記>>
android でも選択したテキストをアラートで表示できた。
test.js
//touchend のタイミングでテキストを保存しておけばいい
selection-text = "global"; //グローバル変数をつくっておく
$(window).on("load", function(e){
$("#iframe").contents().find("div").on("touchend", function(e){
//ここでグローバル変数にテキストを保存しておく
$(this).data('selection-text',window.getSelection());
});
});
touchend 指を離したタイミングでアラートする場合
//touchend のタイミングで取得
$(window).on("load", function(e){
$("#iframe").contents().find("div").on("touchend", function(e){
var selObj = document.getElementById('iframe').contentDocument.getSelection();
alert("選択した文字列: " + selObj);
});
});
