Can Javascript in the form of a bookmarklet or similar, insert the domain of the current page at the position of the cursor? How?
Interested in inserting both stackoverflow.com
, www.stackoverflow.com
as well as just www
.
(Use case: I am writing a question here at SO, the cursor is in either the title text field or the question body text area and I want to insert the domain name at the current position of the cursor).
When focusing the textarea, click the bookmarklet, and use document.activeElement
to identify the textarea, and .slice
its value, concatenating with 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);
})();
If you want the bookmarklet to work for the iframe inside https://robot-parts.confetti.events/
, then access the contentWindow.document
to get to the 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);
})();