I am currently working on a Blazor Server app where I am in need of print functionality. I would like to print a certain element/div on the page using Javascript interop. The problem is that when I try code that usually should work in plain JS, I get an error that the function is not defined.
This is the code I keep in my _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>
This is the C# function that calls the JS code:
public async Task PrintTest() => await _js.InvokeVoidAsync("printDiv");
The element looks like this:
<div id="toprint">
<div id="printdiv" class="print">
<BarcodeGenerator @ref="barcodegen" Code="@place" ElementId="barcode" FullWidth> </BarcodeGenerator>
</div>
</div>
This is the exception that I get: