I made a simple copy-paste component with regular html/css/js. I've tried to turn it into a web component and can no longer get the copy-paste behaviour to work.
The markup inside the shadow DOM is basically
<span contenteditable="true">
<slot></slot>
</span>
<button>Copy</button>
The Javascript:
class CopyPaste extends HTMLElement {
constructor() {
super();
let shadowRoot = this.attachShadow({mode: 'open'});
shadowRoot.appendChild(copyPasteTemplate.content.cloneNode(true));
}
connectedCallback() {
let copyButton = this.shadowRoot.querySelector('button');
let textToCopy = this.shadowRoot.querySelector('span');
function selectElementContents(el) {
var range = document.createRange();
range.selectNodeContents(el);
var sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);
}
function copyText() {
selectElementContents(textToCopy);
document.execCommand('copy');
}
copyButton.addEventListener('click', copyText);
textToCopy.addEventListener('click', copyText);
}
}
window.customElements.define('copy-paste', CopyPaste);
In your example, the textToCopy
variable refers to the <slot>
element, with no text inside.
If you want to get the ditributed node form the light DOM, of the <copy-paste>
element, you should use the assignedNodes()
method of the <slot>
element:
let textToCopy = this.shadowRoot.querySelector('slot').assignedNodes()[0];
PS: note that the contenteditable
attribute may not work as you expect in your given example.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With