我目前正在尝试开发一个基本的浏览器网络,以便使用 qt 框架在特定的互联网站点上冲浪。我创建了一个继承 QWebView 的 MyWindow 类,这是为了处理在新浏览器窗口中打开潜在的弹出窗口。在这个 MyWindow 类中,我还重新创建了 createWindow 函数。此外,我还在 MyWindow 类中创建了 QNetworkAccessManager 和 QNetworkCookieJar 对象,并且没有重新创建任何进一步的新函数。我认为这足以在我的目标网站上冲浪,因为它的主页中有一个登录表单,而您只需使用服务器生成的 cookie 中包含的信息即可在同一网站的其他页面上冲浪登录。它在“正常”导航期间运行良好,而在单击诸如
之类的链接时我总是收到错误<a class="lien_default lienPerso" href="javascript:popupPerso('foo.php?login=bar')">bar</a>
在这种情况下,会提示一个新窗口(我发现javascript函数是一个简单的window.open),但似乎无法从cookie中检索信息:当前 session 未使用,新窗口要求记录-再次进入。只有在这个弹出窗口中登录后,我才能浏览正确的链接页面。我的意图当然是使用当前每个 session 的信息来访问此链接的信息。这种行为(即没有第二次登录请求)实际上是您使用标准浏览器浏览此网页时所得到的。 我还发现,由于 JavaScript 代码,这些链接不是由 linkClicked 信号处理的。
请在我的代码下找到:
main.cpp
#include <QApplication>
#include "mainwindow.h"
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow mWind;
mWind.show();
return a.exec();
}
mywindow.cpp
#include <QWebView>
#include "mywindow.h"
MyWindow::MyWindow (QWidget * parent):QWebView(parent)
{
}
QWebView *MyWindow::createWindow(QWebPage::WebWindowType type)
{
Q_UNUSED(type);
QWebView *webView = new QWebView;
QWebPage *newWeb = new QWebPage(webView);
webView->setAttribute(Qt::WA_DeleteOnClose, true);
webView->setPage(newWeb);
return webView;
}
主窗口.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "mywindow.h"
#include <QWebView>
#include <QWebFrame>
#include <QNetworkAccessManager>
#include <QNetworkCookieJar>
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
QUrl url([url of the website I was targeting]);
ui->setupUi(this);
QWebSettings *settings = ui->w->settings(); // w is an object of MyWindow class that i promoted in Design Panel
settings->setAttribute(QWebSettings::JavascriptEnabled, true);
settings->setAttribute(QWebSettings::PluginsEnabled, true);
settings->setAttribute(QWebSettings::AutoLoadImages, true);
settings->setAttribute(QWebSettings::JavaEnabled, false);
settings->setAttribute(QWebSettings::JavascriptCanOpenWindows, true);
ui->w->page()->setLinkDelegationPolicy(QWebPage::DelegateAllLinks); // This was a test on links
QNetworkCookieJar* cookieJar = new QNetworkCookieJar();
QNetworkAccessManager* nam = new QNetworkAccessManager(this);
nam->setCookieJar(cookieJar);
ui->w->page()->setNetworkAccessManager(nam);
ui->w->load(url);
ui->w->show();
net=nam;
connect(ui->w,SIGNAL(linkClicked(QUrl)),this,SLOT(openUrl(QUrl)));
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::openUrl(QUrl url)
{
QWebView *n = ui->w->createWindow(QWebPage::WebBrowserWindow);
n->page()->setNetworkAccessManager(net);
n->load(url);
n->show();
}
谢谢
希卡鲁斯
最佳答案
在MyWindow::createWindow
中创建的页面似乎没有获取它可以从中获取cookie的networkAccessManager集,请尝试以下操作:
QWebPage *newWeb = new QWebPage(webView);
newWeb->setNetworkAccessManager(page()->networkAccessManager());
另一种选择是创建 QWebPage 的子类,您可以在其中执行此逻辑,而不是在多个位置执行此逻辑,并从 createWindow 返回这样的对象。
关于Javascript 不使用 QWebView cookie/ session ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26325177/