Firefox webextension not copying to clipboard

核能气质少年 提交于 2019-12-11 05:57:25

问题


I have a Firefox web extension which is supposed to generate buttons which copy a link to the clipboard. In my content script for the plugin, I have:

    button.onclick = function() {
        var link = window.location.href.replace(/#[0-9a-zA-Z_]+$/, '') + '#' + id;
        var txtToCopy = document.createElement('input');
        txtToCopy.value = link;
        txtToCopy.select();

        console.log(txtToCopy.value);
        var res = document.execCommand('copy');
        console.log(res);

    }

As you can see, I have it logging the value I'm trying to copy, as well as the result returned from execCommand. Both are what I'd expect.

"https://thing.example.com#12345" true

However, it does not appear to actually copy the text to the clipboard. According to MDN, I shouldn't need any extra permissions as it's is happening in an event, and the response from execCommand makes me thing everything is setup as needed.

I'm running on Ubuntu 16.04, Firefox 51.0.1, with e10s enabled. Maybe e10s is my problem, will give update.


回答1:


You have to append txtToCopy to the DOM to copy from it and it has to be "visible" (more or less).

button.onclick = function() {
    var link = window.location.href.replace(/#[0-9a-zA-Z_]+$/, '') + '#' + id;
    var txtToCopy = document.createElement('input');
    txtToCopy.style.left = '-300px';
    txtToCopy.style.position = 'absolute';
    txtToCopy.value = link;
    document.body.appendChild(txtToCopy);
    txtToCopy.select();

    console.log(txtToCopy.value);
    var res = document.execCommand('copy');
    console.log(res);

    txtToCopy.parentNode.removeChild(txtToCopy);

}


来源:https://stackoverflow.com/questions/42096042/firefox-webextension-not-copying-to-clipboard

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!