designMode/contentEditable を使用したWYSIWYGエディタが、IEのバージョンを8に上げたら正常に動かなくなった、という相談を受けた。ほとんどの機能は正常なのだが、画像の挿入だけがうまくいかないという。
いろいろ調べた結果、execCommand メソッドで InsertImage を実行する前に、対象となる window の focus メソッドを呼び出せば正常に動作することが分かった。
var iframe = document.getElementById('editor'); iframe.contentWindow.document.designMode = 'on'; function insertImage(path) { iframe.contentWindow.focus(); //ココ iframe.contentWindow.document.execCommand('insertimage', false, path); }
問題の解決にあたっては、下記のフォーラムなどで「テキスト選択中なら正常に動く」という証言があったことがヒントになった。
execCommand – specifically InsertImage stops working with IE8 upgrade