Search code examples
javascriptdelphialerttmstms-web-core

How can I execute JavaScript code from Delphi using TMS Web Core?


I've created a simple app with a TWebEdit and a TWebButton on it. I want to call/execute a JavaScript alert() function from within the button that will alert the text from the TWebEdit.

How can I do this?

Obviously, I can't just do the following code as this isn't valid Delphi:

procedure TForm2.WebButton1Click(Sender: TObject);
begin
  alert(WebEdit1.Text);
end;

How can JavaScript code be called from within this button click event?


Solution

  • You can call JavaScript code directly within Delphi using the asm code block:

    procedure TForm2.WebButton1Click(Sender: TObject);
    var
      AlertText: String;
    begin
      AlertText := WebEdit1.Text;
    
      asm
        alert(AlertText);
      end;
    end;
    

    That would work as can be seen by the below screenshots:

    Delphi TMS Web Core app doing a JavaScript alert

    Delphi TMS Web Core app doing a JavaScript alert


    Here's another example with linebreaks:

    procedure TForm2.WebButton1Click(Sender: TObject);
    var
      AlertText: String;
    begin
      AlertText := WebEdit1.Text;
    
      asm
        alert('Your entered text is: \n\n' + AlertText);
      end;
    end;
    

    Delphi TMS Web Core app doing a JavaScript alert