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

调用Blazor JSInterop函数时出现'undefined'错误的原因排查

Blazor Server打印指定元素时JS函数未定义的解决办法

问题原因

你的printDiv函数未挂载到全局window对象上,或是脚本加载顺序错误,导致Blazor的JS互操作无法定位到该函数。

修复步骤

1. 将JS函数暴露到全局作用域

修改_Host.cshtml中的脚本,把函数绑定到window对象上,同时优化打印逻辑(避免内容未加载完成就触发打印):

<script type="text/javascript">
    window.printDiv = function() {
        const targetDiv = document.getElementById("toprint");
        if (!targetDiv) {
            console.error("未找到ID为toprint的元素");
            return;
        }
        const divContents = targetDiv.innerHTML;
        const printWindow = window.open('', '', 'height=600, width=800');
        
        printWindow.document.open();
        printWindow.document.write(`
            <html>
                <head>
                    <!-- 引入页面CSS,保证打印样式与页面一致 -->
                    <link href="css/site.css" rel="stylesheet">
                </head>
                <body>
                    ${divContents}
                </body>
            </html>
        `);
        printWindow.document.close();
        
        // 等待新窗口内容加载完成后执行打印
        printWindow.onload = function() {
            printWindow.print();
            printWindow.close();
        };
    }
</script>

2. 调整脚本加载顺序

确保自定义脚本放在Blazor核心脚本之后,保证Blazor初始化时函数已存在:

<!-- 先加载Blazor核心运行脚本 -->
<script src="_framework/blazor.server.js"></script>
<!-- 再加载自定义打印脚本 -->
<script type="text/javascript">
    // 上述window.printDiv函数代码
</script>

3. 确保调用时机正确

Blazor组件中必须等DOM元素渲染完成后,才能调用打印函数:

  • 按钮触发场景(组件已渲染完成,直接绑定点击事件即可):
<button @onclick="PrintTest">打印</button>
  • 自动触发场景(在OnAfterRenderAsync中调用,确保DOM已生成):
protected override async Task OnAfterRenderAsync(bool firstRender)
{
    if (firstRender)
    {
        await PrintTest();
    }
}

4. 验证C#调用代码

保持原有调用逻辑,确保_js是正确注入的IJSRuntime实例:

@inject IJSRuntime _js

@code {
    public async Task PrintTest() => await _js.InvokeVoidAsync("printDiv");
}

内容的提问来源于stack exchange,提问作者Aladin Ćemalović

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 02:46:05