.linq error while run with LINQPad 9

I have a .linq file script like below

void Main() {
  var sa2 = new SweetAlert2();

  sa2.LoadingShow();

  Thread.Sleep(1000);

  sa2.LoadingClose();
}

public class SweetAlert2 {
  public const string Url_Js = "https://cdn.jsdelivr.net/npm/sweetalert2@11.16.0/dist/sweetalert2.all.min.js";
  public const string Url_Css = "https://cdn.jsdelivr.net/npm/sweetalert2@11.16.0/dist/sweetalert2.min.css";
  private const string SwalLoading = "swalWithLoading";

  public SweetAlert2() {
    Util.HtmlHead.AddScriptFromUri(Url_Js);
    Util.HtmlHead.AddCssLink(Url_Css);
  }

  /// <summary>Show Loading Mask</summary>
  public void LoadingShow(string text = "Please wait...", string title = "Loading...") {
    var js = @$"
var {SwalLoading} = Swal.fire({{
  title: '{title}',
  text: '{text}',
  allowOutsideClick: false,
  showCancelButton: false,
  //position: 'bottom-end',  
  didOpen: () => {{
    Swal.showLoading(); 
  }}
}});
";
    InvokeScript(js);
  }

  /// <summary>Close Loading Mask</summary>
  public void LoadingClose() {
    var js = @$"{SwalLoading}.close();";
    InvokeScript(js);
  }

  public void InvokeScript(string js)
   => Util.InvokeScript(false, "eval", js);
}

In LINQPad 8 (v8.10.4) it works fine, open loading mask and close after 1 second.

But while run in LINQPad 9 (v9.8.12) occur error.
It open loading mask success, but throw JavaScriptException while close loading mask

sa2.LoadingClose();

Answers

  • In LoadingShow, you need to replace var {SwalLoading} with window.{SwalLoading}, and in LoadingClose, replace var js = @$"{SwalLoading}.close();"; with var js = @$"window.{SwalLoading}.close();";

    The reason it worked in LINQPad 8 is because LINQPad 8 ran evals in the global scope. This was changed in LINQPad 9 to improve error handling. In LINQPad 8, the following code returns null; in LINQPad 9, it throws an exception with a useful message:

    Util.JS.Eval ("asdf");
    
  • @JoeAlbahari said:
    In LoadingShow, you need to replace var {SwalLoading} with window.{SwalLoading}, and in LoadingClose, replace var js = @$"{SwalLoading}.close();"; with var js = @$"window.{SwalLoading}.close();";

    The reason it worked in LINQPad 8 is because LINQPad 8 ran evals in the global scope. This was changed in LINQPad 9 to improve error handling. In LINQPad 8, the following code returns null; in LINQPad 9, it throws an exception with a useful message:

    Util.JS.Eval ("asdf");
    

    It works perfectly, thank you.