【发布时间】:2020-10-18 02:04:34
【问题描述】:
我目前正在为一个项目使用 ASP.NET 4.7 网络表单,我正在尝试将后端生成的数据复制到用户客户端计算机。
也就是说,当用户提交表单时,需要将后端生成的代码复制到用户剪贴板中。
这是我的尝试。
Application.aspx.cs
.
.
.
protected void Submit(object sender, EventArgs e)
{
try
{
ClientScript.RegisterStartupScript(GetType(), "hwa", "copyToClipboard("+encodedValue+");", true);
}
catch (Exception ex)
{
}
}
Application.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Application.aspx.cs" Inherits="azureCopyToClipboard.Application" %>
<!DOCTYPE html>
<form id="form1" runat="server">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<div>
<asp:Button ID="SubmitButton" runat="server" class="btn btn-primary " OnClick="Submit" Text="Submit" />
</div>
</body>
</html>
<script type="text/javascript">
function copyToClipboard(textToCopy) {
var textArea;
function isOS() {
//can use a better detection logic here
return navigator.userAgent.match(/ipad|iphone/i);
}
function createTextArea(text) {
textArea = document.createElement('textArea');
textArea.readOnly = true;
textArea.contentEditable = true;
textArea.value = text;
document.body.appendChild(textArea);
}
function selectText() {
var range, selection;
if (isOS()) {
range = document.createRange();
range.selectNodeContents(textArea);
selection = window.getSelection();
selection.removeAllRanges();
selection.addRange(range);
textArea.setSelectionRange(0, 999999);
} else {
textArea.select();
}
}
function copyTo() {
document.execCommand('copy');
document.body.removeChild(textArea);
}
createTextArea(textToCopy);
selectText();
copyTo();
}
</script>
</form>
我使用 ClientScript.RegisterStartupScript 调用客户端函数将编码值粘贴到用户剪贴板...但是由于现代浏览器安全原因,此尝试不起作用,我也没有收到任何客户端错误附加到这个问题。
我试图让这个解决方案同时支持移动和非移动。
【问题讨论】:
-
"is not working" 是一个几乎毫无意义的问题陈述,没有任何调试细节、错误等
-
@charlietfl 抱歉,我认为原因是现代浏览器中的一些安全策略阻止了这种行为......正如 Stackoverflow 上的这个问题中提到的那样stackoverflow.com/questions/400212/…
-
好吧,这是一个基于旧浏览器的老问题......看看developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/…
-
@charlietfl 谢谢,我检查了您发布的 URL,我尝试了两个函数,execCommand() 和 Clipboard API..两者都可以在我的桌面 chrome 上使用我上面的代码......但是不是复制到 iPad 上的剪贴板
-
也是chrome吗?可能仍会在每个浏览器/操作系统的基础上遇到安全问题。好多年没用剪贴板api了
标签: javascript asp.net .net webforms