Tamás Szelei Tamás Szelei - 1 year ago 58
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 (

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


This works in simple cases. However, if I try and load, say, a C++ source file and use that as the parameter of
, 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 Source

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);
  channel->registerObject("doc", Doc);


   new QWebChannel(qt.webChannelTransport,
       function(channel) {
         var doc = channel.objects.doc; // this is "doc" from the registerObject call
         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.