为什么在调用 Blazor JSInterop 函数时收到“未定义”错误?

Why do I get an 'undefined' error when calling Blazor JSInterop function?

提问人:Aladin Ćemalović 提问时间:11/17/2023 更新时间:11/17/2023 访问量:53

问:

我目前正在开发需要打印功能的 Blazor Server 应用。我想使用 Javascript 互操作在页面上打印某个元素/div。问题是,当我尝试通常应该在纯 JS 中工作的代码时,我收到一个错误,即函数未定义。

这是我保留在 _Host.cshtml 中的代码

     <script type="text/javascript">

        async function printDiv() {
            var divContents = document.getElementById("toprint").innerHTML;
            var a = window.open('', '', 'height=500, width=500');
            a.document.open();
            a.document.write('<html>');
            a.document.write('<body > <br>');
            a.document.write(divContents);
            a.document.write('</body></html>');
            a.document.close();
            a.print();
        }
    </script>

这是调用 JS 代码的 C# 函数:

public async Task PrintTest() => await _js.InvokeVoidAsync("printDiv");

该元素如下所示:

    <div id="toprint">
         <div id="printdiv" class="print">
                <BarcodeGenerator @ref="barcodegen" Code="@place" ElementId="barcode" FullWidth>         </BarcodeGenerator>

        </div>
    </div>

这是我得到的例外:

JSInterop 错误

JavaScript C# -服务器端 Blazor-jsinterop

评论

0赞 maciek 11/17/2023
是的,不要在 Blazor 中使用 JS 呈现内容。Blazor Server 在服务器上的线路中保留 DOM 的内部表示形式。通过 JS 修改 DOM 可能会导致未定义的行为。
0赞 Aladin Ćemalović 11/17/2023
好的,您知道如何在不修改 JS 的 DOM 的情况下做到这一点吗?另外有趣的是,当我只留下并删除所有其他写入时,它可以工作......a.document.write(divContents)
0赞 maciek 11/17/2023
是的,使用 html 标记字符串。现在可能会担心。你永远不知道。
0赞 Mister Magoo 11/17/2023
尝试在函数定义中不使用 。@maciek - 此代码不是在修改 DOM - 它正在创建一个新的窗口/文档。async
1赞 Aladin Ćemalović 11/18/2023
@MisterMagoo我已经尝试过了,但仍然遇到相同的异常

答: 暂无答案