从 WebEngine QT 5.13.0 中的 javascript 对话框获取下载文件名

Get Download file Name from a javascript dilog in QWebEngine QT 5.13.0


我使用 QWebEngine 查看网站,出现下载弹出窗口 window,我需要将其下载到我设置的文件夹,我使用此代码,
这是为了获得下载文件的任何信号

ui->widget->load(QUrl(ui->lineEdit->text().trimmed()));
QWebEnginePage *page = ui->widget->page();
QWebEngineProfile *profile = page->profile();
connect(profile, SIGNAL(downloadRequested(QWebEngineDownloadItem*)), this, SLOT(DownloadItem(QWebEngineDownloadItem*)));

然后我开始接受并下载插槽中的文件

void MainWindow::DownloadItem(QWebEngineDownloadItem *item)
{
    item->setPath("D:/amr.pdf");
    connect(item, SIGNAL(finished()), this, SLOT(DownloadFinish()));
    connect(item, SIGNAL(downloadProgress(qint64,qint64)), this, SLOT(downloadProgress(qint64,qint64)));
    item->accept();
    qDebug() << "URL to download = " << item->url().toString();
}

这里的技巧是在我下载文件后,有一个 javascript 文件出现并要求我命名该文件,所以这里的问题是我如何才能得到写在这个文件中的文件名 javascript 对话框,这是它的外观图片 所以我需要一种方法来获取插槽中的文件名或任何东西,这样我就可以使用它来获取这个名称并在我按下确定并开始下载之前命名文件。

谢谢。

Javascript提示window在QWebEnginePage using static QInputDialog::getText. If you want to customize this dialog or do any manipulations with text before it will be returned back to JS, you need to subclass QWebEnginePage and override QWebEnginePage::javaScriptPrompt函数中实现。

这是一个简单的例子:

mywebpage.h

#ifndef MYWEBPAGE_H
#define MYWEBPAGE_H

#include <QObject>
#include <QWebEnginePage>
#include <QWebEngineProfile>

class MyWebPage : public QWebEnginePage
{
public:
    explicit MyWebPage(QWebEngineProfile *profile, QObject *parent = Q_NULLPTR):QWebEnginePage(profile, parent){}

protected:
    bool javaScriptPrompt(const QUrl &securityOrigin, const QString& msg, const QString& defaultValue, QString* result) override;

};

#endif // MYWEBPAGE_H

mywebpage.cpp

#include "mywebpage.h"
#include <QDebug>
#include <QInputDialog>

bool MyWebPage::javaScriptPrompt(const QUrl &securityOrigin, const QString& msg, const QString& defaultValue, QString* result)
{
    bool ok = false;
    QString save_me = QInputDialog::getText(this->view(), tr("MyJavaScript Prompt"), msg, QLineEdit::Normal, defaultValue, &ok);

    //do any manipulations with save_me
    qDebug() << "User entered this string: " << save_me;

    //... and copy it to result
    result->append(save_me);

    return ok;
}

下面是如何将 WebPage 子类设置为 WebView 实例的示例:

auto webview = new QWebEngineView(this);
webview->setPage(new MyWebPage(QWebEngineProfile::defaultProfile(), webview));

//you can test your Prompt here
webview->load(QUrl::fromUserInput("https://www.w3schools.com/Jsref/tryit.asp?filename=tryjsref_prompt"));