Converting Json arrays to HTML tables using the window.chrome.webview.addEventListener feature with a Server Delphi Application

My Delphi application is sending Json data to the embedded Edge browser, but Javascript is reporting a parser error.

https://i.sstatic.net/Z2BUq.png

https://i.sstatic.net/0IIzJ.png

When I modify the value for

Sender.DefaultInterface.PostWebMessageAsJson(PChar(LcTxt));
in Delphi, no message is received in the browser with the alert('Ich bin drin!'). How can this complicated situation be resolved?

Delphi Code:

unit UMain;

interface

uses
  Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, 
  Vcl.Graphics,
  Vcl.Controls, Vcl.Forms, Vcl.Dialogs, WebView2, Winapi.ActiveX, Vcl.StdCtrls,
  Vcl.Edge, Vcl.ExtCtrls;

type
  TForm1 = class(TForm)
  Panel1: TPanel;
  Web: TEdgeBrowser;
  Button1: TButton;
  procedure Button1Click(Sender: TObject);
  procedure WebWebMessageReceived(Sender: TCustomEdgeBrowser;
    Args: TWebMessageReceivedEventArgs);
private
  { Private declarations }
public
  { Public declarations }
end;

var
  Form1: TForm1;

implementation

uses
   system.JSON;

   {$R *.dfm}

procedure TForm1.Button1Click(Sender: TObject);
//WebView2Loader.dll must exist!
var
  LcFile: string;
begin
  //web.Navigate('https://www.embarcadero.com');
  LcFile := ExtractFilePath(ParamStr(0)) + 'WebView2Loader.dll';
  if not FileExists(LcFile) then
    raise Exception.Create('WebView2Loader.dll not exists!');

  LcFile := ExtractFilePath(ParamStr(0)) + 'jsontab.html';
  web.Navigate(LcFile);
end;

procedure TForm1.WebWebMessageReceived(Sender: TCustomEdgeBrowser; Args: 
    TWebMessageReceivedEventArgs);
var
  LoJsArr: TJSONArray;
  Lch    : Char;
  LcTxt  : string;
begin
  LoJsArr := TJSONArray.Create;
  try
    Lch := 'A';
    for LcTxt in ['red', 'green', 'Blue'] do //green
    begin
      // a)
      //   LoJsArr.Add(LcTxt);
      // b)
      //   LoJsArr.Add(TJSONObject.Create(TJSONPair.Create(Lch, LcTxt)));
      // c)
           LoJsArr.Add(TJSONObject.Create(TJSONPair.Create('name', LcTxt)));
      Lch := succ(Lch);
    end;
    // a) LoJsArr.ToJSON === '["rot","gr\u00FCn","Blau"]'
    // b) LoJsArr.ToJSON === '[{"A":"rot"},{"B":"gr\u00FCn"},{"C":"Blau"}]'
    // c) LoJsArr.ToJSON === '[{"name":"rot"},{"name":"gr\u00FCn"},{"name":"Blau"}]'

    LcTxt := LoJsArr.ToJSON;

    Sender.DefaultInterface.PostWebMessageAsJson(PChar(LcTxt));
  finally
    LoJsArr.Free;
  end;
 end;
end.

HTML Code (jsontab.html) Code-Transfer new XMLHttpRequest():

 <blink>
 <?xml version="1.0"?>
 <!DOCTYPE html>
 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="de" lang="de">
 <head>
 <script>
    window.chrome.webview.addEventListener('message', arg => 
    {
      alert('Ich bin drin!');
      let step = 1;
      let text = '';
      try 
      {
        const myObj = JSON.parse(arg.data);
        step = 2;
        text = "<table border='1'>"
        for (let x in myObj) {
           text += "<tr><td>" + myObj[x].name + "</td></tr>";
        }
        step = 3;
        text += "</table>"    
      }
      catch (e)
      {
        step =  'Error: ' + e.message;
      }
      alert('step: ' + step);
      document.getElementById("demo").innerHTML = text;       
    });

    function XClick(id) 
    {
      /* Server request xmlhttp.send("..");  */
      window.chrome.webview.postMessage(id);
    }
  </script>
  </head>
  <body>
     <h2>Make a table based on JSON data.</h2>
     <input id="btn" type="button" value="Request" onclick="XClick(this.id);" />
     <p id="demo"></p>
 </body>
 </html>
 </blink>

Answer №1

Special thanks to @AmigoJack

  attempt
  {
    move = 2;
    wording = '<table border="1">\n';  // Linebreaks are useful for debugging purposes
    for (let x in arg.data)
    {
      // Avoid accidentally inserting HTML where only text is expected (XSS)
      wording += '<tr><td>'
           + arg.data[x].name.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;')
           + '</td></tr>\n';
    }
    move = 3;
    wording += '</table>';
  }
  catch (e)
  {
    // Provide more detailed information, such as our progress so far
    move = 'Error: ' + e.message
         + '\nStep: ' + move
         + '\nData: ' + arg.data
         + '\nText: ' + wording;
  }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Linking an element's class to the focus of another element in Angular

In my Angular application, I have multiple rows of elements that are wrapped with the myelement directive (which is a wrapper for the input tag). To highlight or focus on one of these elements at a time, I apply the .selected class in the styles. Everythi ...

What methods can be used to perform unit testing on a controller within an AngularJS Directive?

My command is: window.map.directive('dosingFrequencies', [ function() { return { restrict: 'E', scope: true, templateUrl: '/views/directives/dosingFrequencies.html', controller: function($scope, ...

How can we handle multiple asynchronous calls within a function?

In the process of developing a dynamic page with heavy AJAX interactions that update values in selectors based on prior selections. Currently, working on implementing a "repopulate" feature to fill in selectors based on previous entries. Whenever Selector ...

"Addressing the issue of ineffective form validation for empty or whitespace inputs

I've been working on creating a form and everything seems to be going well except for the validation aspect. It doesn't highlight when intentionally left blank or filled with spaces. I have included "required" in the HTML which partially achieves ...

Using jQuery to input a value that returns the [object Object]

While working with jQuery in asp.net, I encountered an issue where the value assigned to a hidden field (hfstockcode) is returning [object Object]. The console output shows v.fn.v.init[1]. How can I retrieve the correct value for the hidden field? $(docum ...

What is the best way to implement autoplay sound on a JavaScript webpage?

I'm currently working on a web system aimed at monitoring values from a database, and I have the requirement to trigger a sound alert when a specific range of values is received. Despite trying various examples found online, none of them have been suc ...

Encountering issues accessing REST API services on the Oracle Business Intelligence Publisher 12.2.1.2.0 server

Currently, I have an operational Oracle Business Intelligence Publisher 12.2.1.2.0 server and my aim is to utilize the REST API services for accessing a specific report (i.e., TestReport) on the server using the Postman tool. I have been experimenting with ...

Obtain the value of a URL parameter on a webpage without needing to refresh the

I have a list of records on a webpage, each with a unique URL pointing to another page with a parameter in the URL. When any of these records are clicked, I want to display the value of the URL parameter in an alert without reloading the page. <script& ...

Dawn Break Alarm Timepiece - Online Platform

My buddy recently purchased a "sunrise alarm clock" that gradually brightens to mimic a sunrise and make waking up easier. I had the thought of replicating this effect with my laptop, but I've been facing issues with getting the JavaScript time funct ...

Is it possible for me to use ts files just like I use js files in the same manner?

So I recently stumbled upon TypeScript and found it intriguing, especially since I enjoy adding annotations in my code. The only downside is that I would have to change all my .js files to .ts files in order to fully utilize TypeScript's capabilities. ...

Obtain the API by navigating through nested dynamic routes in Next.js

Can someone help me with the folder structure in NEXT JS for pages/api/product/[id]/index.js? What would be the URL to access the Api index in the [id] folder? Here is my folder structure pages/ api/ product/ [id]/ index.js I nee ...

What are the available choices for constructing HTML based on an ajax response?

Are there any alternatives or libraries available for constructing html from an ajax response? Currently, I am taking the json data received, creating the html as a string, and using a jQuery function to insert it into the DOM. However, I believe there mu ...

There seems to be an issue with converting JsonArray to JsonObject in Android

This is the code that I have experimented with so far: <?php include('connectdb.php'); $sql = "SELECT salesordercard_code, location_from, location_to, salesmancode FROM salesorderingcard"; $result = mysql_query($sql); ...

Develop a video in mp4 format using Node.js and ffmpeg by combining two or more jpg images

I am currently working on a video animator project where I generate .jpg images from an html canvas tag and then use these images as frames for the video. The tool I am using for video generation is ffmpeg. Successful with Single Image const ffmpeg = req ...

Utilize Laravel in conjunction with AngularJs by implementing a base path in place of the current one when using ng-src

Let me try to explain my issue clearly. I am delving into using angularJs in my Laravel project for the first time. The controller is responsible for fetching the uploaded photos from the database. public function index() { JavaScript::put([ ...

Exploring the wonders of retrieving JSON data in PHP through an Ajax request

A front-end developer is sending an array of data formatted as a JSON object using an Ajax call. The JSON object structure is shown below: { "name": " Test Name ", "image_url": "test URL", "include": [ "1" ], "dimension": [ null ], "media_type" ...

Exploring the power of makeStyles in Material UI when combined with TypeScript

I am currently in the process of converting a JavaScript template to Typescript. Here is an example of my accordionStyle.ts file: import { primaryColor, grayColor } from "../../material-dashboard-pro-react"; const accordionStyle = (theme?:an ...

Error: Unable to locate sportsRecord due to missing function

updated answer1: Greetings, I have updated the question with some detailed records and console logs for better understanding. sportsRecord = { playerTigers:[ {TigerNo: 237, TigerName: "Bird Bay Area", TigerkGroupNo: 1, isDefault: true ...

Setting up a textarea tooltip using highlighter.js

I'm experimenting with using highlighter.js within a textarea. I've customized their sample by substituting the p with a textarea enclosed in a pre tag (for right-to-left language settings). <div class="article" style="width: 80%; height: 80% ...

Is it feasible to modify a JavaScript value through the PHP GET method?

My HTML file contains the following JavaScript code: var a=["","#"] I want to append a value after the # symbol by specifying that value in the website URL. For example: site.com/#value Therefore, the updated JavaScript code will be: var a=["","#va ...