QWebEnginePage Class

  • Header: QWebEnginePage

  • CMake:

    find_package(Qt6 REQUIRED COMPONENTS WebEngineCore)

    target_link_libraries(mytarget PRIVATE Qt6::WebEngineCore)

  • qmake: QT += webenginecore

  • Inherits: QObject

Detailed Description

A web engine page holds the contents of an HTML document, the history of navigated links, and actions.

QWebEnginePage's API is very similar to QWebEngineView, as you are still provided with common functions like action() (known as pageAction() in QWebEngineView), triggerAction(), and findText().

A page can be loaded using load() or setUrl(). Alternatively, if you have the HTML content readily available, you can use setHtml(). The GET method is always used to load URLs.

The QWebEnginePage class also offers methods to retrieve both the URL currently loaded by the page (see url()) as well as the URL originally requested to be loaded (see requestedUrl()). These methods make possible the retrieval of the URL before and after a DNS resolution or a redirection occurs during the load process. The requestedUrl() also matches to the URL added to the page history (QWebEngineHistory) if load is successful.

The title of an HTML page can be accessed with the title() property. Additionally, a page may also specify an icon, which can be accessed using the icon() or its URL using the iconUrl() property. If the title or the icon changes, the corresponding titleChanged(), iconChanged() and iconUrlChanged() signals will be emitted. The zoomFactor() property enables zooming the contents of the web page by a scale factor.

The loadStarted() signal is emitted when the page begins to load, whereas the loadProgress() signal is emitted whenever an element of the web page completes loading, such as an embedded image or a script. The loadFinished() signal is emitted when the page contents have been loaded completely, independent of script execution or page rendering. Its argument, either true or false, indicates whether or not the load operation succeeded.

An HTML document is loaded in a main frame within the web page. If it references child frames (as defined by the <frame> or <iframe> elements), they are considered part of the content. Child frames are individually accessible only through JavaScript.

Web sites define security origin for safely accessing each other's resources for client-side scripting or databases. An origin consist of a host name, a scheme, and a port number. For example, the sites http://www.example.com/my/page.html and http://www.example.com/my/overview.html are allowed to share the same database or access each other's documents when used in HTML frame sets and JavaScript. At the same time, http://www.malicious.com/evil.html is prevented from accessing the resources of http://www.example.com/, because they are of a different security origin. By default, local schemes like file:// and qrc:// are considered to be in the same security origin, and can access each other's resources. Local resources are by default restricted from accessing remote content, which means that file:// will not be able to access http://domain.com/foo.html.

Scripts can be executed on the web page by using runJavaScript(), either in the main JavaScript world, along with the rest of the JavaScript coming from the web contents, or in their own isolated world. While the DOM of the page can be accessed from any world, JavaScript variables of a function defined in one world are not accessible from a different one. QWebEngineScript::ScriptWorldId provides some predefined IDs for this purpose. Using the runJavaScript() version without the world ID is the same as running the script in the MainWorld.

The FocusOnNavigationEnabled setting can be used to make the view associated with the page automatically receive focus when a navigation operation occurs (like loading or reloading a page or navigating through history).

Member Type Documentation

 

enum QWebEnginePage::Feature

This enum describes the platform feature access categories that the user may be asked to grant or deny access to:

Constant

Value

Description

QWebEnginePage::Notifications

0

Web notifications for the end-user.

QWebEnginePage::Geolocation

1

Location hardware or service.

QWebEnginePage::MediaAudioCapture

2

Audio capture devices, such as microphones.

QWebEnginePage::MediaVideoCapture

3

Video devices, such as cameras.

QWebEnginePage::MediaAudioVideoCapture

4

Both audio and video capture devices.

QWebEnginePage::MouseLock

5

Mouse locking, which locks the mouse pointer to the web view and is typically used in games.

QWebEnginePage::DesktopVideoCapture (since Qt 5.10)

6

Video output capture, that is, the capture of the user's display, for screen sharing purposes for example.

QWebEnginePage::DesktopAudioVideoCapture (since Qt 5.10)

7

Both audio and video output capture.

See Also

enum QWebEnginePage::FileSelectionMode

This enum indicates whether the implementation of the chooseFiles() function should return only one file or may return multiple files:

Constant

Value

Description

QWebEnginePage::FileSelectOpen

0

Return only one file name.

QWebEnginePage::FileSelectOpenMultiple

1

Return multiple file names.

QWebEnginePage::FileSelectUploadFolder

2

Allows users to specify a single existing folder for upload.

QWebEnginePage::FileSelectSave

3

Specify a new file to be created.

See Also

See also chooseFiles()

enum QWebEnginePage::FindFlag

flags QWebEnginePage::FindFlags

This enum describes the options available to the findText() function. The options can be OR-ed together from the following list:

Constant

Value

Description

QWebEnginePage::FindBackward

1

Searches backwards instead of forwards.

QWebEnginePage::FindCaseSensitively

2

By default findText() works case insensitive. Specifying this option changes the behavior to a case sensitive find operation.

The FindFlags type is a typedef for QFlags<FindFlag>. It stores an OR combination of FindFlag values.

enum QWebEnginePage::JavaScriptConsoleMessageLevel

This enum describes the different severity levels a JavaScript console message can have:

Constant

Value

Description

QWebEnginePage::InfoMessageLevel

0

The message is purely informative and can safely be ignored.

QWebEnginePage::WarningMessageLevel

1

The message informs about unexpected behavior or errors that may need attention.

QWebEnginePage::ErrorMessageLevel

2

The message indicates there has been an error.

enum QWebEnginePage::LifecycleState

This enum describes the lifecycle state of the page:

Constant

Value

Description

QWebEnginePage::LifecycleState::Active

0

Normal state.

QWebEnginePage::LifecycleState::Frozen

1

Low CPU usage state where most HTML task sources are suspended.

QWebEnginePage::LifecycleState::Discarded

2

Very low resource usage state where the entire browsing context is discarded.

See Also

enum QWebEnginePage::NavigationType

Constant

Value

Description

QWebEnginePage::NavigationTypeLinkClicked

0

The navigation request resulted from a clicked link.

QWebEnginePage::NavigationTypeTyped

1

The navigation request resulted from an explicitly loaded URL.

QWebEnginePage::NavigationTypeFormSubmitted

2

The navigation request resulted from a form submission.

QWebEnginePage::NavigationTypeBackForward

3

The navigation request resulted from a back or forward action.

QWebEnginePage::NavigationTypeReload

4

The navigation request resulted from a reload action.

QWebEnginePage::NavigationTypeRedirect (since Qt 5.14)

6

The navigation request resulted from a content or server controlled redirect. This also includes automatic reloads.

QWebEnginePage::NavigationTypeOther

5

The navigation request was triggered by other means not covered by the above.

See Also

enum QWebEnginePage::PermissionPolicy

This enum describes the permission policies that the user may set for data or device access:

Constant

Value

Description

QWebEnginePage::PermissionUnknown

0

It is unknown whether the user grants or denies permission.

QWebEnginePage::PermissionGrantedByUser

1

The user has granted permission.

QWebEnginePage::PermissionDeniedByUser

2

The user has denied permission.

See Also

enum QWebEnginePage::RenderProcessTerminationStatus

This enum describes the status with which the render process terminated:

Constant

Value

Description

QWebEnginePage::NormalTerminationStatus

0

The render process terminated normally.

QWebEnginePage::AbnormalTerminationStatus

1

The render process terminated with with a non-zero exit status.

QWebEnginePage::CrashedTerminationStatus

2

The render process crashed, for example because of a segmentation fault.

QWebEnginePage::KilledTerminationStatus

3

The render process was killed, for example by SIGKILL or task manager kill.

enum QWebEnginePage::WebAction

This enum describes the types of action which can be performed on the web page.

Actions only have an effect when they are applicable.

The availability of actions can be be determined by checking isEnabled() on the action returned by action().

Constant

Value

Description

QWebEnginePage::NoWebAction

- 1

No action is triggered.

QWebEnginePage::Back

0

Navigate back in the history of navigated links.

QWebEnginePage::Forward

1

Navigate forward in the history of navigated links.

QWebEnginePage::Stop

2

Stop loading the current page.

QWebEnginePage::Reload

3

Reload the current page.

QWebEnginePage::ReloadAndBypassCache

10

Reload the current page, but do not use any local cache.

QWebEnginePage::Cut

4

Cut the content currently selected into the clipboard.

QWebEnginePage::Copy

5

Copy the content currently selected into the clipboard.

QWebEnginePage::Paste

6

Paste content from the clipboard.

QWebEnginePage::Undo

7

Undo the last editing action.

QWebEnginePage::Redo

8

Redo the last editing action.

QWebEnginePage::SelectAll

9

Select all content. This action is only enabled when the page's content is focused. The focus can be forced by the JavaScript window.focus() call, or the FocusOnNavigationEnabled setting should be enabled to get automatic focus.

QWebEnginePage::PasteAndMatchStyle

11

Paste content from the clipboard with current style.

QWebEnginePage::OpenLinkInThisWindow (since Qt 5.6)

12

Open the current link in the current window.

QWebEnginePage::OpenLinkInNewWindow (since Qt 5.6)

13

Open the current link in a new window. Requires implementation of createWindow() or newWindowRequested().

QWebEnginePage::OpenLinkInNewTab (since Qt 5.6)

14

Open the current link in a new tab. Requires implementation of createWindow() or newWindowRequested().

QWebEnginePage::OpenLinkInNewBackgroundTab (since Qt 5.7)

31

Open the current link in a new background tab. Requires implementation of createWindow() or newWindowRequested().

QWebEnginePage::CopyLinkToClipboard (since Qt 5.6)

15

Copy the current link to the clipboard.

QWebEnginePage::CopyImageToClipboard (since Qt 5.6)

17

Copy the clicked image to the clipboard.

QWebEnginePage::CopyImageUrlToClipboard (since Qt 5.6)

18

Copy the clicked image's URL to the clipboard.

QWebEnginePage::CopyMediaUrlToClipboard (since Qt 5.6)

20

Copy the hovered audio or video's URL to the clipboard.

QWebEnginePage::ToggleMediaControls (since Qt 5.6)

21

Toggle between showing and hiding the controls for the hovered audio or video element.

QWebEnginePage::ToggleMediaLoop (since Qt 5.6)

22

Toggle whether the hovered audio or video should loop on completetion or not.

QWebEnginePage::ToggleMediaPlayPause (since Qt 5.6)

23

Toggle the play/pause state of the hovered audio or video element.

QWebEnginePage::ToggleMediaMute (since Qt 5.6)

24

Mute or unmute the hovered audio or video element.

QWebEnginePage::DownloadLinkToDisk (since Qt 5.6)

16

Download the current link to the disk. Requires a slot for downloadRequested().

QWebEnginePage::DownloadImageToDisk (since Qt 5.6)

19

Download the highlighted image to the disk. Requires a slot for downloadRequested().

QWebEnginePage::DownloadMediaToDisk (since Qt 5.6)

25

Download the hovered audio or video to the disk. Requires a slot for downloadRequested().

QWebEnginePage::InspectElement (since Qt 5.6)

26

Trigger any attached Web Inspector to inspect the highlighed element.

QWebEnginePage::ExitFullScreen (since Qt 5.6)

27

Exit the fullscreen mode.

QWebEnginePage::RequestClose (since Qt 5.6)

28

Request to close the web page. If defined, the window.onbeforeunload handler is run, and the user can confirm or reject to close the page. If the close request is confirmed, windowCloseRequested is emitted.

QWebEnginePage::Unselect (since Qt 5.7)

29

Clear the current selection.

QWebEnginePage::SavePage (since Qt 5.7)

30

Save the current page to disk. MHTML is the default format that is used to store the web page on disk. Requires a slot for downloadRequested().

QWebEnginePage::ViewSource (since Qt 5.8)

32

Show the source of the current page in a new tab. Requires implementation of createWindow() or newWindowRequested().

QWebEnginePage::ToggleBold (since Qt 5.10)

33

Toggles boldness for the selection or at the cursor position. Requires contenteditable="true".

QWebEnginePage::ToggleItalic (since Qt 5.10)

34

Toggles italics for the selection or at the cursor position. Requires contenteditable="true".

QWebEnginePage::ToggleUnderline (since Qt 5.10)

35

Toggles underlining of the selection or at the cursor position. Requires contenteditable="true".

QWebEnginePage::ToggleStrikethrough (since Qt 5.10)

36

Toggles striking through the selection or at the cursor position. Requires contenteditable="true".

QWebEnginePage::AlignLeft (since Qt 5.10)

37

Aligns the lines containing the selection or the cursor to the left. Requires contenteditable="true".

QWebEnginePage::AlignCenter (since Qt 5.10)

38

Aligns the lines containing the selection or the cursor at the center. Requires contenteditable="true".

QWebEnginePage::AlignRight (since Qt 5.10)

39

Aligns the lines containing the selection or the cursor to the right. Requires contenteditable="true".

QWebEnginePage::AlignJustified (since Qt 5.10)

40

Stretches the lines containing the selection or the cursor so that each line has equal width. Requires contenteditable="true".

QWebEnginePage::Indent (since Qt 5.10)

41

Indents the lines containing the selection or the cursor. Requires contenteditable="true".

QWebEnginePage::Outdent (since Qt 5.10)

42

Outdents the lines containing the selection or the cursor. Requires contenteditable="true".

QWebEnginePage::InsertOrderedList (since Qt 5.10)

43

Inserts an ordered list at the current cursor position, deleting the current selection. Requires contenteditable="true".

QWebEnginePage::InsertUnorderedList (since Qt 5.10)

44

Inserts an unordered list at the current cursor position, deleting the current selection. Requires contenteditable="true".

QWebEnginePage::ChangeTextDirectionLTR (since Qt 6.6)

45

Changes text direction to left-to-right in the focused input element.

QWebEnginePage::ChangeTextDirectionRTL (since Qt 6.6)

46

Changes text direction to right-to-left in the focused input element.

enum QWebEnginePage::WebWindowType

This enum describes the types of window that can be created by the createWindow() function:

Constant

Value

Description

QWebEnginePage::WebBrowserWindow

0

A complete web browser window.

QWebEnginePage::WebBrowserTab

1

A web browser tab.

QWebEnginePage::WebDialog

2

A window without decoration.

QWebEnginePage::WebBrowserBackgroundTab (since Qt 5.7)

3

A web browser tab without hiding the current visible WebEngineView.

Property Documentation

 

audioMuted : bool

This property holds whether the current page audio is muted.

The default value is false.

Access functions:

  • bool isAudioMuted() const

  • void setAudioMuted(bool muted)

Notifier signal:

See Also

See also recentlyAudible

backgroundColor : QColor

This property holds the page's background color behind the document's body.

You can set the background color to Qt::transparent or to a translucent color to see through the document, or you can set it to match your web content in a hybrid application to prevent the white flashes that may appear during loading.

The default value is white.

Access functions:

  • backgroundColor() const

  • void setBackgroundColor(const &color)

[read-only] contentsSize : const QSizeF

This property holds the size of the page contents.

Access functions:

  • contentsSize() const

Notifier signal:

  • void contentsSizeChanged(const &size)

[read-only] hasSelection : const bool

This property holds whether this page contains selected content or not.

Access functions:

  • bool hasSelection() const

See Also

See also selectionChanged()

[read-only] icon : const QIcon

This property holds the icon associated with the page currently viewed.

By default, this property contains a null icon. If touch icons are disabled (see QWebEngineSettings::TouchIconsEnabled), the favicon is provided in two sizes (16x16 and 32x32 pixels) encapsulated in QIcon. Otherwise, single icon is provided with the largest available size.

Access functions:

  • icon() const

Notifier signal:

See Also

[read-only] iconUrl : const QUrl

This property holds the URL of the icon associated with the page currently viewed.

By default, this property contains an empty URL.

Access functions:

  • iconUrl() const

Notifier signal:

See Also

See also iconUrlChanged(), icon(), iconChanged()

lifecycleState : LifecycleState

This property holds the current lifecycle state of the page.

The following restrictions are enforced by the setter:

  • A visible page must remain in the Active state.

  • If the page is being inspected by a devToolsPage then both pages must remain in the Active states.

  • A page in the Discarded state can only transition to the Active state. This will cause a reload of the page.

These are the only hard limits on the lifecycle state, but see also recommendedState for the recommended soft limits.

Access functions:

  • lifecycleState() const

  • void setLifecycleState( state)

Notifier signal:

  • void lifecycleStateChanged( state)

See Also

[read-only, since 6.2] loading : const bool

This property holds whether the page is currently loading.

This property was introduced in Qt 6.2.

Access functions:

  • bool isLoading() const

Notifier signal:

See Also

[read-only] recentlyAudible : const bool

This property holds the current page's audible state, that is, whether audio was recently played or not.

The default value is false.

Access functions:

  • bool recentlyAudible() const

Notifier signal:

See Also

See also audioMuted

[read-only] recommendedState : const LifecycleState

This property holds the recommended limit for the lifecycle state of the page.

Setting the lifecycle state to a lower resource usage state than the recommended state may cause side-effects such as stopping background audio playback or loss of HTML form input. Setting the lifecycle state to a higher resource state is however completely safe.

Access functions:

  • recommendedState() const

Notifier signal:

  • void recommendedStateChanged( state)

See Also

[read-only] renderProcessPid : const qint64

This property holds the process ID (PID) of the render process assigned to the current page's main frame.

If no render process is available yet, 0 is returned.

Access functions:

  • renderProcessPid() const

Notifier signal:

[read-only] requestedUrl : const QUrl

This property holds the URL that was originally requested to be loaded by the page that is currently viewed.

The URL may differ from the one returned by url(), which is the actual URL that results from DNS resolution or redirection.

Access functions:

  • requestedUrl() const

See Also

See also url(), setUrl()

[read-only] scrollPosition : const QPointF

This property holds the scroll position of the page contents.

Access functions:

  • scrollPosition() const

Notifier signal:

  • void scrollPositionChanged(const &position)

[read-only] selectedText : const QString

This property holds the text currently selected.

By default, this property contains an empty string.

Access functions:

  • selectedText() const

See Also

See also selectionChanged()

[read-only] title : const QString

This property holds the title of the page as defined by the HTML <title> element.

If the page has no <title> element, then the URL is used instead. For file:// URLs only the filename is used and not the full path.

By default, before any content has been loaded, this property contains an empty string.

Access functions:

  • title() const

See Also

See also titleChanged()

url : QUrl

This property holds the URL of the page currently viewed.

Setting this property clears the view and loads the URL.

By default, this property contains an empty, invalid URL.

Access functions:

  • url() const

  • void setUrl(const &url)

Notifier signal:

See Also

See also urlChanged()

visible : bool

This property holds whether the page is considered visible in the Page Visibility API.

Setting this property changes the Document.hidden and the Document.visibilityState properties in JavaScript which web sites can use to voluntarily reduce their resource usage if they are not visible to the user.

If the page is connected to a view then this property will be managed automatically by the view according to it's own visibility.

Access functions:

  • bool isVisible() const

  • void setVisible(bool visible)

Notifier signal:

  • void visibleChanged(bool visible)

See Also

See also lifecycleState

zoomFactor : qreal

This property holds the zoom factor for the page content.

Valid values are within the range from 0.25 to 5.0. The default factor is 1.0.

Access functions:

  • zoomFactor() const

  • void setZoomFactor( factor)

Member Function Documentation

 

void QWebEnginePage::runJavaScript(const QString &scriptSource, const std::function<void (const QVariant &)> &resultCallback)

void QWebEnginePage::runJavaScript(const QString &scriptSource, quint32 worldId = 0, const std::function<void (const QVariant &)> &resultCallback = {})

Runs the JavaScript code contained in scriptSource without checking whether the DOM of the page has been constructed. If you need more control over how the script is run, consider using scripts() instead.

To avoid conflicts with other scripts executed on the page, the world in which the script is run is specified by worldId. The world ID values are the same as provided by QWebEngineScript::ScriptWorldId, and between 0 and 256. If you leave out the world ID, the script is run in the MainWorld.

When the script has been executed, resultCallback is called with the result of the last executed statement. resultCallback can be any of a function pointer, a functor or a lambda, and it is expected to take a QVariant parameter. For example:

 
Sélectionnez
page.runJavaScript("document.title", [](const QVariant &amp;v) { qDebug() &lt;&lt; v.toString(); });

Only plain data can be returned from JavaScript as the result value. Supported data types include all of the JSON data types as well as, for example, Date and ArrayBuffer. Unsupported data types include, for example, Function and Promise.

Do not execute lengthy routines in the callback function, because it might block the rendering of the web engine page.

We guarantee that the callback (resultCallback) is always called, but it might be done during page destruction. When QWebEnginePage is deleted, the callback is triggered with an invalid value and it is not safe to use the corresponding QWebEnginePage or QWebEngineView instance inside it.

See Also

[explicit] QWebEnginePage::QWebEnginePage(QObject *parent = nullptr)

Constructs an empty QWebEnginePage with the parent parent.

QWebEnginePage::QWebEnginePage(QWebEngineProfile *profile, QObject *parent = nullptr)

Constructs an empty web engine page in the web engine profile profile with the parent parent.

If the profile is not the default profile, the caller must ensure that the profile stays alive for as long as the page does.

[virtual] QWebEnginePage::~QWebEnginePage()

Destroys the web page.

[virtual protected] bool QWebEnginePage::acceptNavigationRequest(const QUrl &url, QWebEnginePage::NavigationType type, bool isMainFrame)

This function is called upon receiving a request to navigate to the specified url by means of the specified navigation type type. isMainFrame indicates whether the request corresponds to the main frame or a child frame. If the function returns true, the navigation request is accepted and url is loaded. The default implementation accepts all navigation requests.

Navigation requests can be delegated to the Qt application instead of having the HTML handler engine process them by overloading this function. This is necessary when an HTML document is used as part of the user interface, and not to display external data, for example, when displaying a list of results.

This function is not called for fragment navigation on the same page. Such navigation, for example, happens by clicking a link to a '#fragment' within the page. It does not trigger a load to a different document, even though it changes page's url and adds history entry. It only serves as a shortcut to scroll within the page. Hence, no delegation of this navigation type is expected to happen.

The loading process is started and the loadStarted() signal is emitted before the request is accepted or rejected. Therefore, a loadFinished() signal that returns false is to be expected even after delegating the request.

When using setHtml or setContent with relative links, make sure to specify a base url, otherwise the links will be considered invalid and no navigation requests will be emitted.

The QWebEngineUrlRequestInterceptor class offers further options for intercepting and manipulating requests.

QAction *QWebEnginePage::action(QWebEnginePage::WebAction action) const

Returns a QAction for the specified WebAction action.

The action is owned by the