gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 23:27:59 24 4
gpt4 key购买 nike


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

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 对话框中写入的文件名,这是一个图像它看起来怎么样 enter image description here所以我需要一种方法来获取插槽中的文件名或其他任何内容,这样我就可以在按“确定”并开始下载之前使用它来获取该名称并命名该文件。

谢谢。

最佳答案

Javascript提示窗口在QWebEnginePage中实现使用静态QInputDialog::getText 。如果你想自定义这个对话框或者在它返回到 JS 之前对文本进行任何操作,你需要子类 QWebEnginePage并覆盖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"));

关于javascript - 从 WebEngine QT 5.13.0 中的 javascript 对话框获取下载文件名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56646927/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com