我最近第一次创建了一个 Chrome 扩展。我的页面上有一个复制按钮,当扩展程序作为网页加载时,该按钮可以正常工作。但是,当我将其作为扩展加载时,复制功能不起作用。
我的 manifest.json
权限如下所示:
"permissions": [
"webNavigation",
"storage",
"clipboardWrite",
"clipboardRead"
]
要复制的 popout.html
页面中的代码如下所示:
<div id="legacyCopyLabel">
<a onclick="copyText(getElementById('legacy'))" class="alignright">COPY</a>
</div>
我的 JavaScript 代码中的 copyText()
函数如下所示:
function copyText(element) {
var range, selection, worked;
if (document.body.createTextRange) {
range = document.body.createTextRange();
range.moveToElementText(element);
range.select();
} else if (window.getSelection) {
selection = window.getSelection();
range = document.createRange();
range.selectNodeContents(element);
selection.removeAllRanges();
selection.addRange(range);
}
try {
document.execCommand('copy');
updateStatus ('Copied address', 'info');
}
catch (err) {
alert('Unable to copy the address');
}
}
如果您想查看完整代码,请参见:https://github.com/markallisongit/handcash-chrome
Chrome 扩展程序位于此处的 Chrome 商店:https://chrome.google.com/webstore/detail/handcash-handle-converter/bnkohbkbipagdhplhkhgonbalbjigpoh
最佳答案
它不起作用,因为您使用内联JS:<a onclick="...">
。
根据 Chrome 内容安全警察的说法:
Inline JavaScript will not be executed. This restriction bans both inline blocks and inline event handlers (e.g. ).
解决方案是将您的代码放入单独的 .js
中文件并将其作为普通的 JS 脚本包含进来。
关于javascript - 如何使用链接复制到 Chrome 扩展中的剪贴板?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52027110/