runjavascript async->sync

This commit is contained in:
xiaoyifang 2021-12-01 22:26:33 +08:00 committed by yifang
parent 5f86c33f8d
commit 9b179dac3c
2 changed files with 16 additions and 11 deletions

View file

@ -181,16 +181,22 @@ QString ArticleView::runJavaScriptSync(QWebEnginePage* frame, const QString& var
qDebug(QString("runJavascriptScriptSync with :%1").arg(variable).toLatin1().data()); qDebug(QString("runJavascriptScriptSync with :%1").arg(variable).toLatin1().data());
QString result; QString result;
QEventLoop loop; //QEventLoop loop;
QObject::connect(this, SIGNAL(notifyJavascriptFinished()), &loop, SLOT(quit())); //QObject::connect(this, SIGNAL(notifyJavascriptFinished()), &loop, SLOT(quit()));
frame->runJavaScript(variable, [&](const QVariant &v) QSharedPointer<QEventLoop> loop = QSharedPointer<QEventLoop>(new QEventLoop());
QTimer::singleShot(1000, loop.data(), &QEventLoop::quit);
frame->runJavaScript(variable, [loop,&result](const QVariant &v)
{ {
if(v.isValid()) if(loop->isRunning()){
result = v.toString(); if(v.isValid())
emitJavascriptFinished(); result = v.toString();
loop->quit();
}
//this->emitJavascriptFinished();
}); });
loop.exec(); loop->exec();
return result; return result;
} }
@ -326,7 +332,7 @@ ArticleView::ArticleView( QWidget * parent, ArticleNetworkAccessManager & nm,
//connect( &inspectAction, SIGNAL( triggered() ), this, SLOT( inspect() ) ); //connect( &inspectAction, SIGNAL( triggered() ), this, SLOT( inspect() ) );
QWebEngineView *m_pNewView; QWebEngineView *m_pNewView;
QWebEnginePage *page = ui.definition; QWebEnginePage *page = ui.definition->page();
connect(&inspectAction, &QAction::triggered, this, [page, m_pNewView]() mutable connect(&inspectAction, &QAction::triggered, this, [page, m_pNewView]() mutable
{ {
m_pNewView = new QWebEngineView(); m_pNewView = new QWebEngineView();
@ -2605,8 +2611,7 @@ QString ArticleView::getWebPageTextSync(QWebEnginePage * page){
QString planText; QString planText;
QEventLoop loop; QEventLoop loop;
page->toPlainText([&](const QString & result){ page->toPlainText([&](const QString & result){
if(result.valid()) planText = result;
planText = result;
loop.quit(); loop.quit();
}); });
@ -2783,7 +2788,7 @@ QString ArticleView::insertSpans( QString const & html )
QString ArticleView::checkElement( QWebEnginePage & page, QPoint const & pt ) QString ArticleView::checkElement( QWebEnginePage & page, QPoint const & pt )
{ {
return runJavaScriptSync(page, QString( return runJavaScriptSync(&page, QString(
" var a= document.elementFromPoint(%1,%2);" " var a= document.elementFromPoint(%1,%2);"
"var nodename=a.nodeName.toLowerCase();" "var nodename=a.nodeName.toLowerCase();"
"if(nodename==\"body\"||nodename==\"html\"||nodename==\"head\")" "if(nodename==\"body\"||nodename==\"html\"||nodename==\"head\")"

Binary file not shown.