gpt4 book ai didi

javascript - 从 Chrome 应用中的剪贴板获取当前文本

转载 作者:行者123 更新时间:2023-11-30 12:28:14 24 4
gpt4 key购买 nike

我正在寻找如何在 Chrome 应用程序中使用 javascript 简单地从剪贴板获取当前文本。虽然我做了一些搜索,但我无法找到一个最新的、完整的和适应各种场景的解决方案。所以,我想我会在这里提出并回答这个问题,以期对其他人有所帮助。

以下是一些相关问题(从最相关到​​最不相关):

最佳答案

这适用于 Chrome 39 及更高版本。

首先,您需要将“clipboardRead”权限放入 list 文件的权限部分。有关详细信息,请参阅以下链接:https://developer.chrome.com/apps/manifesthttps://developer.chrome.com/apps/declare_permissions

然后,你可以使用这个函数:

// getClipboardText - return any text that is currently on the clipboard
function getClipboardText() {
// create div element for pasting into
var pasteDiv = document.createElement("div");

// place div outside the visible area
pasteDiv.style.position = "absolute";
pasteDiv.style.left = "-10000px";
pasteDiv.style.top = "-10000px";

// set contentEditable mode
pasteDiv.contentEditable = true;

// find a good place to add the div to the document
var insertionElement = document.activeElement; // start with the currently active element
var nodeName = insertionElement.nodeName.toLowerCase(); // get the element type
while (nodeName !== "body" && nodeName !== "div" && nodeName !== "li" && nodeName !== "th" && nodeName !== "td") { // if have not reached an element that it is valid to insert a div into (stopping eventually with 'body' if no others are found first)
insertionElement = insertionElement.parentNode; // go up the hierarchy
nodeName = insertionElement.nodeName.toLowerCase(); // get the element type
}

// add element to document
insertionElement.appendChild(pasteDiv);

// paste the current clipboard text into the element
pasteDiv.focus();
document.execCommand('paste');

// get the pasted text from the div
var clipboardText = pasteDiv.innerText;

// remove the temporary element
insertionElement.removeChild(pasteDiv);

// return the text
return clipboardText;
}

关于javascript - 从 Chrome 应用中的剪贴板获取当前文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28618766/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com