我在后台脚本中执行此操作:
var link = document.createElement('div');
那么链接为空。我猜这是因为扩展后台页面没有 DOM,或者我无权访问它? 无论如何,我需要这个来复制到剪贴板。这是我尝试使用它的部分:
function selectionOnClick(info, tab) {
var link = document.createElement('div');
var range = document.createRange();
link.innerHTML = ShortURL(info.selectionText);
range.selectNode(link);
window.getSelection().addRange(range);
try {
var successful = document.execCommand('copy');
if (!successful) {
alert("Your browser doesn't support copy to clipboard.");
}
} catch(err) {
alert("Your browser doesn't support copy to clipboard.");
}
window.getSelection().removeAllRanges();
link.parentNode.removeChild(link);
}
chrome.contextMenus.create({'title': 'Short selected', 'contexts':['selection'], 'onclick':selectionOnClick});
最佳答案
您已创建该节点,但尚未将其附加到任何内容。将其附加到正文:
document.getElementsByTagName('body').appendChild(link);
关于javascript - 如何在后台脚本中创建元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42134888/