script defined above does gives script1006 due to the if condition clause. If you change the "distance<0" clause to true, everything works. I am guessing something in the razor engine may be causing this or I might be missing something simple.
Here is the script that does not return a script 1006
I think you have found a bug. The < character in your original scripts leads to invalid JavaScript in the generated .g.cs file. Repro code:
<script>
Blazor.registerFunction('JavaScriptAlert', (message) => {
var distance = 5;
if (distance < 0) {
alert(message);
}
return true;
});
</script>
Result in .g.cs:
builder.OpenElement(8, "script");
builder.AddContent(9, @"
Blazor.registerFunction('JavaScriptAlert', (message) => {
var distance = 5;
if (distance ");
builder.AddContent(10, "< 0) {\n alert(message);\n }\n\n return true;\n });\n");
builder.CloseElement();
Workaround: Replace < in JavaScript with <. After that change, generated JavaScript is correct and works as expected.
@SteveSandersonMS can you confirm that this is a bug? Or is this intended behavior and special characters like < have to be escaped in Blazor templates?
Thanks for reporting this.
Firstly, you're correct that the misinterpretation of the < character does look like a Razor parser bug.
However, putting <script> elements inside Blazor components is almost always a mistake. Blazor components are added and removed dynamically, and that's not compatible with <script> tags in general, whose effects cannot be removed by removing them from the document.
I'll file a separate issue to track prevention of <script> elements inside Blazor components. That will address the underlying issue better.
Filed aspnet/AspNetCore#16218
Most helpful comment
Thanks for reporting this.
Firstly, you're correct that the misinterpretation of the
<character does look like a Razor parser bug.However, putting
<script>elements inside Blazor components is almost always a mistake. Blazor components are added and removed dynamically, and that's not compatible with<script>tags in general, whose effects cannot be removed by removing them from the document.I'll file a separate issue to track prevention of
<script>elements inside Blazor components. That will address the underlying issue better.