Loading of a page via GET request in QWebView is unsuccessful

My attempt to fetch a website using a GET request in JavaScript within QWebView is causing an error when I use jQuery.ajax. However, switching to XMLHttpRequest seems to solve the issue.

Here is the revised JavaScript code:

var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
        var data = jQuery.parseXML(xmlhttp.responseText);
        alert(data);
    } else if (xmlhttp.readyState == 4) {
        alert(JSON.stringify(xmlhttp));
    }
}

xmlhttp.open("GET", CO_SERVICE, true);
xmlhttp.setRequestHeader("Authorization", "Basic " + btoa("user:password"));
xmlhttp.send();

The code works perfectly in Chrome. However, when I run my Qt application and load the file using:

QNetworkProxyFactory::setUseSystemConfiguration(true);

ui->webView->load(QUrl("qrc:///index.html"));
ui->webView->show();

I encounter the following error:

Can you help me identify what mistake I might be making?

Answer №1

Here is the solution that I used and worked well:

JavaScript

this.completed = function (result) {
    console.log(result);
};

getRequest.done.connect(this, completed);
getRequest.get("url", "username", "password");

C++

MainWindow.h

private:
    Ui::MainWindow *ui;
    GetRequest* mGetRequest;

private slots:
    void addJSObject();

MainWindow.cpp

mGetRequest = new GetRequest();

QObject::connect(ui->webView->page()->mainFrame(), SIGNAL(javaScriptWindowObjectCleared()), this, SLOT(addJSObject()));

ui->webView->load(QUrl("qrc:/index.html"));


void MainWindow::addJSObject() {
    ui->webView->page()->mainFrame()->addToJavaScriptWindowObject(QString("getRequest"), mGetRequest);
}

GetRequest.h

#ifndef GETREQUEST_H
#define GETREQUEST_H

#include <QObject>
#include <QString>

#include <QNetworkReply>
#include <QNetworkAccessManager>

class GetRequest : public QObject {
    Q_OBJECT

public:
    explicit GetRequest(QObject *parent = 0);
    ~GetRequest();

public slots:
    void get(QString url, QString username, QString password);

signals:
    void done(QString result);

private:
    QNetworkAccessManager* mNetworkAccessManager;

private slots:
    void replyFinished(QNetworkReply* networkReply);
};

#endif // GETREQUEST_H

GetRequest.m

#include "getrequest.h"

GetRequest::GetRequest(QObject *parent) : QObject(parent) {
    mNetworkAccessManager = new QNetworkAccessManager(this);
    QObject::connect(mNetworkAccessManager, SIGNAL(finished(QNetworkReply*)), this, SLOT(replyFinished(QNetworkReply*)));
}

GetRequest::~GetRequest() {
    delete mNetworkAccessManager;
}

void GetRequest::get(QString url, QString username, QString password) {
    QUrl u(url);
    u.setUserName(username);
    u.setPassword(password);

    mNetworkAccessManager->get(QNetworkRequest(u));
}

void GetRequest::replyFinished(QNetworkReply* networkReply) {
    QString result(networkReply->readAll());

    emit done(result);

    delete networkReply;
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is it possible to write a text file in UTF-16 using Javascript?

I need to create a UTF-16 text file from a string. For instance: var s = "aosjdfkzlzkdoaslckjznx"; var file = "data:text/plain;base64," + btoa(s); The above code generates a UTF-8 encoding text file. How can I modify it to produce a UTF-16 text file usin ...

html form submission error - please refresh

After submitting a form on my page, I keep encountering an error every time I try to refresh the page. I've attempted several solutions that I came across online, but none of them have resolved the issue as I continue to face this error on different ...

Is there a way to send a boolean to a directive and activate a function when that boolean is altered, all without using $watch?

My goal was to achieve something akin to the following simplified example: class ButtonController { set isFoo(value) { console.log(value); // do something here } } angular.module('myApp', []).directive('mButton', () => ...

Combining Images and Navigation in Next.js using Tailwind CSS

I am facing an issue where the image from a particular section overlaps with the Navbar dropdown on mobile devices. Adding z-50 to the navbar did not solve the problem as expected. What I want is for the image to remain below the dropdown menu when it is ...

Is it possible to generate a basic HTML page using Express JS without utilizing Ejs or any other templating engine

I have a basic HTML file with a Bootstrap form, along with a simple API coded within. In my server.js file, I've specified that when I request /about, it should redirect me to the about.html page. However, instead of redirecting, I'm encountering ...

Unveiling the secrets of leveraging Vue Router global navigation guard to efficiently verify multiple conditions

Within a Vue 3 application utilizing Pinia, my objective is to accomplish the following: Direct a user to the sign-in page when authentication is not verified. Direct a user to a verification page if authenticated but not yet verified. Direct a user to th ...

Discover a method to receive an alert when the mouse exits the inner window along the y-axis

Is there a way to receive an alert if the mouse moves out of the inner window solely in the y-axis? Currently, alerts are triggered when the mouse moves out on both x-axis and y-axis. For example, if the mouse pointer hovers over the address bar coming fro ...

Navigate to a different page in NextJs without causing a page refresh or altering the current state of the application

Recently, I encountered a challenge in my NextJS application while attempting to incorporate dynamic routes as endpoints on my server. Specifically, when accessing localhost:3000/register, the register.tsx file is loaded successfully. However, within one ...

PHP fails to recognize Ajax POST requests

Here is a function I have created to submit forms: function submit_form(form) { $( form ).submit(function(e) { // Prevent form submission e.preventDefault(); // Get the form instance ...

Removing Specific Items from a List in React: A Step-by-Step Guide

I have developed a basic ToDo List App. The functionality to display tasks from the input form is working correctly, but I am facing issues with deleting tasks when the Delete button is clicked. export class TaskList extends Component { constructor(pr ...

Ways to display the ChaptersButton in Videojs-Player

I'm trying to incorporate videojs (version 8.10.0) into my project and provide viewers with a way to select chapters within the video. According to the official documentation, it seems that simply including a track element linking to a VTT file within ...

Storing data in a JSON format

Our team requires a service that can periodically generate up-to-date JSON data every 15 minutes for our AJAX services to consume. This JSON will be used for metric analysis and charts among other things. The reason behind the 15-minute interval is due to ...

Navigating in a react login interface

Recently, I developed a backend code for a login system that verifies the validity of usernames and passwords. While everything is functioning as intended, I am facing an issue with automating the redirect to /dashboard. The client side operates on Port ...

Retrieving JSON Arrays in PHP through an AJAX Request

Having trouble extracting data from multiple arrays in an AJAX request. Can anyone help? Here's what I'm trying to send: https://i.stack.imgur.com/4MEL4.png Executing a jQuery AJAX POST to a PHP file, but uncertain how to retrieve the data. An ...

What steps can I take to prevent the [Vue warn]: Potential infinite update loop detected in a component render function issue in my VueJS project?

What are some tips to prevent an infinite update loop in a component render function using VUEJS? I have created a simple show password button with the following structure: <div class="mt-4 switchContainerGenPassword"> <div class="switchGene ...

Is there a way to transform an HTML canvas into a tangible photograph?

I am currently working on converting HTML content into a real image on the client's side. After conducting research on canvas2base64, canvas2base64, and html2base64 on Stack Overflow, I have found that the generated images are always based on base64 c ...

Iterate over a specified range of elements within a list using jQuery

Hello everyone, I am new to JQuery and facing a challenge. I am attempting to iterate through a list in jQuery that was sent from a servlet to JSP, starting from a specific index to another one. However, my attempts have been unsuccessful so far. Here is ...

What steps are necessary for caching an external XML file?

I have taken over a maintenance project in WordPress and I am working on parsing external XML. The previous developer had already set up a system for this, but I am wondering if it is the most efficient way or if I should implement my own solution. The cu ...

Is it possible to apply action.payload to multiple keys within an object?

My plan for updating tasks in my Todo app is as follows: addTask: (state, action) => { const newTask = { id: uniqueId(), text: action.payload, completed: false, date: action.payload, }; state.push(newTas ...

Issue with child component not reflecting changes when the state is updated

In an attempt to pass a value to a child component, I am encountering an issue where the value does not update when the parent component's value changes. Below is my code: Child Component: class Test extends Component { constructor(props) { su ...