Tamás Szelei Tamás Szelei - 3 months ago 18
C++ Question

How can I escape a string to ensure that it is a valid string literal in JS source?

I have a Qt application that embeds a web browser (

QWebEngineView
). I would like to call a javascript function with a string argument from the C++ application. The means of doing this is calling

page()->runJavaScript("setContent(\"hello\");");


This works in simple cases. However, if I try and load, say, a C++ source file and use that as the parameter of
setContent
, this will break, because I can't simply assemble the string like this:

auto js = QString("setContent(\"%1\");").arg(fileStr);


I tried the following:

fileStr = fileStr.replace('"', "\\\"");
fileStr = fileStr.replace("\n", "\\n");


But apparently this could not escape the string, I get an error when I call this javascript. How can I universally escape a long string with newlines and possible special characters so that I can construct a valid js fragment like this?

Answer

So, after some research, I came across QWebChannel which is meant for bi-directional communication between the application and the hosted webpage. The imported qwebchannel.js in the examples can be found here. From there, this is what I did:

In C++:

  auto channel = new QWebChannel(this);
  page()->setWebChannel(channel);
  channel->registerObject("doc", Doc);

In HTML/JS:

   new QWebChannel(qt.webChannelTransport,
       function(channel) {
         var doc = channel.objects.doc; // this is "doc" from the registerObject call
         editor.setValue(doc.text);
         doc.textChanged.connect(updateText); // textChanged is a signal of the class of doc.
       }
   );

So, even though this does not directly answer the question, what is presented here can be used to achieve the same effect.