You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Blazor Assembly中如何实现选中文本一键粘贴至指定输入框?

实现方案说明

你需要借助JavaScript来实现这个功能,Blazor C#无法直接访问浏览器的文本选中或剪贴板API,必须通过JS互操作完成。

具体实现步骤

1. 添加JavaScript函数

在wwwroot/index.html的<body>末尾添加以下JS代码,用来获取页面中选中的文本:

<script>
    window.getSelectedText = () => {
        return window.getSelection().toString();
    };
</script>

如果需要读取系统剪贴板的内容(而非页面选中的文本),可以替换为以下异步函数(注意:仅在HTTPS/localhost环境下可用,部分场景需用户授权):

<script>
    window.getClipboardContent = async () => {
        try {
            return await navigator.clipboard.readText();
        } catch (error) {
            console.error('读取剪贴板失败:', error);
            return '';
        }
    };
</script>

2. Blazor组件代码

注入IJSRuntime,实现按钮点击逻辑,调用JS函数获取文本并赋值给对应输入框:

@inject IJSRuntime JSRuntime

<div>
    <input type="text" @bind="@inputValueA" placeholder="输入框A" />
    <button @onclick="PasteToInputA">粘贴到A</button>
</div>

<div style="margin-top: 10px;">
    <input type="text" @bind="@inputValueB" placeholder="输入框B" />
    <button @onclick="PasteToInputB">粘贴到B</button>
</div>

@code {
    private string inputValueA { get; set; } = string.Empty;
    private string inputValueB { get; set; } = string.Empty;

    private async Task PasteToInputA()
    {
        // 若使用剪贴板版本,替换为"getClipboardContent"
        var targetText = await JSRuntime.InvokeAsync<string>("getSelectedText");
        inputValueA = targetText;
    }

    private async Task PasteToInputB()
    {
        var targetText = await JSRuntime.InvokeAsync<string>("getSelectedText");
        inputValueB = targetText;
    }
}

原理说明

浏览器的文本选中、剪贴板访问属于原生DOM API范畴,Blazor的C# WebAssembly运行时无法直接调用这些浏览器专属能力,必须通过JS互操作(IJSRuntime)桥接C#和浏览器JS环境,才能完成这类操作。

内容的提问来源于stack exchange,提问作者rick britto

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 18:52:09