テキストを挿入するUserScript
引数
text: 入力したいテキスト
cursor: テキストを入力する<textarea>
scrapboxなら#text-input
スマホでも動くようにしたver.ですtakker.icon /icons/感謝.iconyosider.icon
code:script.js
export function insertText({text}) {
const cursor = document.getElementById('text-input');
cursor.focus();
これで動く
code:script.js
cursor.value = text;
こっちでも動くけど長い
code:script.js_alternative
const start = cursor.selectionStart; // in this case maybe 0
cursor.setRangeText(text);
cursor.selectionStart = cursor.selectionEnd = start + text.length;
code:script.js
const uiEvent = document.createEvent('UIEvent');
uiEvent.initEvent('input', true, false);
cursor.dispatchEvent(uiEvent);
}
code:script.js_old
export function insertText({text,cursor}) {
const isFirefox = () => {
const userAgent = window.navigator.userAgent.toLowerCase();
if (userAgent.indexOf('firefox') != -1) {
return true;
}
return false;
};
cursor.focus();
if (isFirefox()) {
const start = cursor.selectionStart; // in this case maybe 0
cursor.setRangeText(text);
cursor.selectionStart = cursor.selectionEnd = start + text.length;
const uiEvent = document.createEvent('UIEvent');
uiEvent.initEvent('input', true, false);
cursor.dispatchEvent(uiEvent);
} else {
だからここで条件分岐を使っている
code:script.js_old
document.execCommand('insertText', false, text);
}
}