PDA

View Full Version : Call JavaScript function with parameters from Qt C++



qt_developer
31st July 2014, 16:27
I know how can I call a JavaScript function without parameters from Qt C++ code:

JavaScript code:



function foo() {
console.log("bar");
}


Qt code:



QString foo = "foo(); null";
ui->webView->page()->mainFrame()->evaluateJavaScript(foo);


I want to call a JavaScript fuction with parameters from Qt C++ code. How can I do it? It's possible to perform a pass parameters?

Best regards.

anda_skoa
1st August 2014, 07:04
If the parameter value can be expressed as a string, you could simple make it part of the "script"



const QString scriptWithPlaceHolders = "foo(%1);";

evaluateJavaScrpt(scriptWithPlaceHolders.arg(argum ent));


Cheers,
_

xeyos
12th January 2015, 17:30
Im having some problems with this.
Ive got this code

const QString scriptWithPlaceHolders = "test();null";
((std::pair<QWebView*, std::string>)publicWindows.at(0)).first->page()->mainFrame()->evaluateJavaScript(scriptWithPlaceHolders);
over this javascript

function test(){
document.getElementById("title").innerHTML = ":(";
}

And everything seems fine, but if i try:


const QString scriptWithPlaceHolders = "test(%1);null";
((std::pair<QWebView*, std::string>)publicWindows.at(0)).first->page()->mainFrame()->evaluateJavaScript(scriptWithPlaceHolders.arg(":("));
over


function test(purq){
document.getElementById("title").innerHTML = ":(";
}

it does not work, any idea on what can be wrong?

wysota
12th January 2015, 19:09
Please explain how "does not work" manifest itself.

sulliwk06
12th January 2015, 20:37
If I were a betting man, I would bet you need to include some escaped quotations so that your parameter gets passed as a string to your function.

xeyos
13th January 2015, 00:31
does not work was function not being called, but sulliwk was right it worked doing this:
evaluateJavaScript(scriptWithPlaceHolders.arg("':('"));
Some wasted hours blaming everything else xD. But i really cant understand why is that even needed, more when thinking on javascript and his weak typing.
Thank you dudes.