由于目前在一个项目中使用ASP.NET4.7webforms,我正在尝试将在后端生成的数据复制到用户的客户端计算机。
换句话说,当用户提交表单时,在后端生成的代码需要复制到用户剪贴板。
这是我的尝试。
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>
im使用ClientScript.RegisterStartupScript调用客户端函数将编码值粘贴到用户剪贴板...但是由于现代浏览器安全原因,此尝试无效,我也没有得到任何客户端错误附加到此问题。
我试图使这个解决方案同时支持移动和非移动。
不幸的是,大多数浏览器不会允许您在没有适当的用户操作的情况下写入剪贴板,例如在按钮单击事件中。否则,它可能被用于恶意目的;任何网站都可以把他们想要的东西写进你的剪贴板,只需访问网站即可。在您的情况下,由于您进行了异步HTTP操作,您的按钮单击会丢失它自己的事件上下文,并且在服务器响应的成功回调函数中,您不再具有写入剪贴板的权限。
我想建议的是,大多数网站正在做的是;在一个漂亮的大模式窗口中显示结果代码,带有一个漂亮的“复制到剪贴板”按钮。