DevWizard
DevWizard

Reputation: 695

javascript copy content of a div into clipboard from a canvas doesn't work on Firefox

I need to copy the content of a popup into the clipboard as is inside a canvas (it's Openlayer 4 stuff, you add an overlay to the map and then you can use a div to parse it as a content once is created) and is not directly accessible.

to display the popup you need to click on a street restriction.

here the project:

https://www.traffwebdev.uk/parking/test.html

This code works in Chrome, Internet explorer and in Edge but not in Firefox.

Here the code I'm using to copy the content into the clipboard:

      const copyEv = () => {
        let max = ''
        if ($('#numofdivs').length > 0) {
          max = $('#numofdivs').val()
        }
        else {
          max = $('#popup-content').children().length
        }

        for (let i = 0; i < max; i++) {
          document.getElementById(`Copy_Btn_${i}`).addEventListener('click', () => {
            // We will need a range object and a selection.
            let contentHolder = document.getElementById(`info_${i}`)
            let range = document.createRange()
            let selection = window.getSelection()

            // Clear selection from any previous data.
            selection.removeAllRanges()

            // Make the range select the entire content of the contentHolder paragraph.
            range.selectNodeContents(contentHolder)

            // Add that range to the selection.
            selection.addRange(range)

            // Copy the selection to clipboard.
            document.execCommand('copy')

            // Clear selection if you want to.
            selection.removeAllRanges()
          })
        }
      }

I found a different method but neither is working, in the codepen is working and if I modify the text to copy with the content of the popup also is working (you can inspect the popup and copy the whole info_0 in the codepen) but in a real life doesn't work.

https://codepen.io/chriscoyier/pen/OXAwvq

The copyEv function is called after the popup is displayed on the map with a delay of 300ms to make sure the popup is shown

The code is converted with webpack once is on production.

Upvotes: 0

Views: 639

Answers (1)

Randy Casburn
Randy Casburn

Reputation: 14165

Try this: make the element containing the text editable by adding the contenteditable attribute prior to selecting/copying text. You can remove the attribute just after the copy command is executed.

Firefox is finicky about selecting content from non-content-editable elements in the DOM.

Upvotes: 1

Related Questions