在JavaScript中,可以通过navigator.clipboard
API来调用浏览器的剪贴板功能,实现复制文本到剪贴板或者从剪贴板读取文本。此外,还可以使用window.open()
方法打开新窗口,或者使用window.location
对象来导航到新的URL,这些都可以看作是调用浏览器的快捷功能。
以下是一些具体的应用示例:
function copyToClipboard(text) {
if (navigator.clipboard && navigator.clipboard.writeText) {
return navigator.clipboard.writeText(text);
} else {
// 兼容旧版浏览器的方法
var textArea = document.createElement("textarea");
textArea.value = text;
document.body.appendChild(textArea);
textArea.select();
try {
var successful = document.execCommand('copy');
var msg = successful ? 'successful' : 'unsuccessful';
console.log('Copying text command was ' + msg);
} catch (err) {
console.log('Oops, unable to copy', err);
}
document.body.removeChild(textArea);
}
}
function openNewWindow(url) {
window.open(url, '_blank');
}
function navigateToUrl(url) {
window.location.href = url;
}
navigator.clipboard.writeText()
之前,检查是否有权限,并引导用户授权。navigator.clipboard
API的旧版浏览器,可以使用document.execCommand('copy')
方法作为备选方案。但请注意,这种方法可能不是最可靠的,并且在某些情况下可能无法正常工作。领取专属 10元无门槛券
手把手带您无忧上云