Javascript 能否以书签或类似的形式,在光标位置插入当前页面的域?怎么办?
有兴趣同时插入 stackoverflow.com
、www.stackoverflow.com
以及 www
。
(用例:我在这里写一个问题,光标在标题文本字段或问题正文文本区域,我想在光标的当前位置插入域名)。
最佳答案
聚焦textarea时,点击小书签,使用document.activeElement
来识别textarea,.slice
它的值,与window.location连接.origin
:
javascript: (() => {
const textarea = document.activeElement;
const { selectionStart } = textarea;
textarea.value = textarea.value.slice(0, selectionStart) + window.location.origin + textarea.value.slice(selectionStart);
})();
如果您希望小书签适用于 https://robot-parts.confetti.events/
中的 iframe,请访问 contentWindow.document
以获取activeElement
:
javascript: (() => {
const textarea = document.querySelector('.signup-iframe').contentWindow.document.activeElement;
const { selectionStart } = textarea;
textarea.value = textarea.value.slice(0, selectionStart) + window.location.origin + textarea.value.slice(selectionStart);
})();
关于Javascript:如何在光标的当前位置插入域?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59065000/