PDA

View Full Version : Problem with evaluateJavaScript



Fred
23rd January 2016, 15:42
Hello!

I have a problem with an injected JavaScript and I don't know why it doesn't work as expected. I use a QWebView and after loading is finished of the current website, I want to inject a JavaScript.

Here a shorted version of the script:


QString injectedScript =

"alert('First alert');"

"function JSGetElement () {"
"alert('Clicked');"
"}"

"function JSOnMouseMove (event) {"
// Making something
"}"

"var body = document.body;"
"body.onclick = function () { JSGetElement(); };"
"body.onmousemove = function () { JSOnMouseMove (event); };"
;

QString one =
"var headID = document.head;"
"var newScript = document.createElement('script');"
"newScript.type = 'text/javascript';"
"newScript.innerHTML = " + injectedScript + ";"
"headID.appendChild(newScript);"
;
ui->webView->page()->mainFrame()->evaluateJavaScript(one);

The script works if an alert box appears when you click on the website.

But if you remove the first line ("alert('First alert');") the script doesn't work anymore and no alert box appears when you click on the website. Can anybody say me why this happen or how I must change the script that it works without the first line?

Thank you.

anda_skoa
23rd January 2016, 15:52
I am no expert on JavaScript but are you sure you don't need any separation between the end of one function declaration and the beginning of the next?

I.e. is this really valid JavaScript code?


function foo() {}function bar() {}var baz = somevalue;


Cheers,
_

Fred
23rd January 2016, 16:30
Hi anda_skoa,

Thank you for your fast reply. I don't know if the style of the JavaScript is good or bad, but it works. After searching over two hours for a solution I found it now. All I need is to wrap the complete script into a self running function:


(function(){ ... })();

I don't know why this is necessary because the script is nested in a <script>...</script>. When I insert the script manually in a local saved website it works without this.

However now it works :)