Problem with evaluateJavaScript
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:
Code:
"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); };"
;
"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.
Re: Problem with evaluateJavaScript
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?
Code:
function foo() {}function bar() {}var baz = somevalue;
Cheers,
_
Re: Problem with evaluateJavaScript
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:
Code:
(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 :)