PDA

View Full Version : runJavaScript() crashes my program.



ayanda83
19th November 2016, 21:38
I am trying to extract some data from an HTML document but for some reason my program crashes because of the code below. the program crashes when I capture the variable info_data in my lambda function. any help would be appreciated.


QString WebView::retData_Html()
{
QVariant info_data;

this->page()->runJavaScript("function retContactDetails(){"
"var x = document.getElementsByClassName(\"result\");"

"var detailsArray = [];"
"var companyName;"
"var contactNumer;"
"var address;"

"var i;"
"for(i = 0; i < x.length; i++){"

"var child_nodes = x[i].children;"

"var j;"
"for(j = 0; j < child_nodes.length; j++){"

"if(child_nodes[j].className == \"resultName\"){"
"companyName = child_nodes[j].firstElementChild.innerHTML;}"

"else if(child_nodes[j].className == \"resultAddress\"){"
"address = child_nodes[j].textContent;}"

"else if(child_nodes[j].className == \"resultContact\"){"
"contactNumer = child_nodes[j].firstElementChild.textContent;}"

"}"
"detailsArray.push(companyName);"
"detailsArray.push(address);"
"detailsArray.push(contactNumer);"

"}"

"return detailsArray.toString();"
"}"
"retContactDetails();",[&info_data](const QVariant &infoData){info_data = infoData/*qDebug() << infoData.toString() <<endl*/;});

return info_data.toString();

}

anda_skoa
20th November 2016, 11:04
& in the capture list means the variable is captured by reference.

The variable in question is allocated on the stack, it ceases to exist when the scope of the function ends.

So you lambda access memory that is no longer accessible.

Either capture a heap allocated variable or one that is a member of the class.

Cheers,
_

ayanda83
21st November 2016, 08:17
Thanks, wouldn't have known that, still new to C++ 11 concepts.

anda_skoa
21st November 2016, 09:35
Also, since the method needs a callback instead of having a return value, it might call the lambda asychronously.
So your return value might sometimes or always be an empty string right now.

Cheers,
_

ayanda83
21st November 2016, 10:42
I've noticed that and I've been wondering what courses it. Is there a better solution then? One that is not going to return an empty string.

anda_skoa
21st November 2016, 14:45
Well, theoretically a nested event loop.

But better would of course be to not force a synchronous behavior onto an asynchronous operation.

Cheers,
_