0

I have a simple button on my ASP.NET MVC view:

<input type="button" onclick="print()" value="Print" />

Which on click calls this JavaScript function:

<script type="text/javascript" language="javascript">
    function print() {
        window.print();
    }
</script>

However when I click the "Print" button I get the following error:

96:252 Uncaught RangeError: Maximum call stack size exceeded
    at print (96:252)
    at print (96:252)
    at print (96:252)
    at print (96:252)
    at print (96:252)
    at print (96:252)
    at print (96:252)
    at print (96:252)
    at print (96:252)
    at print (96:252)

I'm not exactly sure what those numbers are refering to, but I am at least sure that they are not lines in my code. I don't have a line 252 and on 96 there is just a <dt> tag.

I have also tried this:

<input type="button" onclick="window.print()" value="Print" />

and this:

<input type="button" onclick="javascript:window.print()" value="Print" />

and this:

<asp:Button ID="btnPrint" runat="server" Text="Print" OnClientClick="javascript:print();" />

But got the same error (the third try I can't even get the asp:Button to appear). Now I know the error means that in the code I am calling a function which in turn calls another function and so forth, until it hits the call stack limit. However, I'm not sure why my code is causing this to happen.

If I try to not use the button at all and simply add:

<script>
    window.print();
</script>

At the bottom of the view then everything works, but this is not the desired behavior. It should only print if the user clicks the button.

Why is my code causing this error? What can I change to fix it?

2
  • When you tried this, had you removed your function that's also named print? <input type="button" onclick="window.print()" value="Print" /> Commented Jun 23, 2021 at 19:50
  • 1
    Omg.... No but that fixed it. I feel foolish now. I can either delete this question or if you want to make an answer and say this so I can give you credit I'd be happy to. Commented Jun 23, 2021 at 19:53

1 Answer 1

1

Functions without a declared scope are scoped to global (window). Don't name your function print unless it's sitting as a member of some other object or something, or otherwise in a scope, or you basically overwrite the real one.

Either rename your function, or just call

<input type="button" onclick="window.print()" value="Print" />

Be sure your function named print is no longer in scope.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.