OVERVIEW
The wxWebView component enables a web browser to be embedded into wxWidgets forms and allow us to manipulate the content in the browser. Depending on the OS, wxWebView either uses Edge or Webkit as its underlying browser engine.
In order for the wxWebView component to be available, it should have been enabled during the installation of wxWidgets. Given below is sample code to load https://www.imdb.com and then inject javascript to do a search for a movie.
SAMPLE CODE
browser.h
#include <wx/wxprec.h>
#ifndef WX_PRECOMP
#include <wx/wx.h>
#endif // WX_PRECOMP
#if !wxUSE_WEBVIEW_WEBKIT && !wxUSE_WEBBIEW_WEBKIT2 && !wxUSE_WEBVIEW && !wxUSE_WEBVIEW_EDGE
#error "A wxWebView backend is required"
#endif
#include <wx/webview.h>
class Browser:public wxFrame {
public:
Browser(const wxString& title);
virtual void OnCloseWindow(wxCloseEvent& evt);
void OnNavigationComplete(wxWebViewEvent &evt);
void OnDocumentLoaded(wxWebViewEvent &evt);
private:
wxWebView *m_web;
};
browser.cpp
#include "browser.h"
Browser::Browser(const wxString& title):
wxFrame(NULL, -1, title, wxDefaultPosition, wxSize(1000,400)) {
Bind(wxEVT_CLOSE_WINDOW, &Browser::OnCloseWindow, this);
Bind(wxEVT_WEBVIEW_NAVIGATED, &Browser::OnNavigationComplete, this);
Bind(wxEVT_WEBVIEW_LOADED, &Browser::OnDocumentLoaded, this);
wxPanel *pan = new wxPanel(this);
wxBoxSizer *vbox = new wxBoxSizer(wxVERTICAL);
pan->SetSizer(vbox);
m_web = wxWebView::New();
m_web->Create(pan, -1, wxT("https://www.imdb.com"), wxDefaultPosition, wxDefaultSize);
vbox->Add(m_web, 1, wxEXPAND | wxALL);
Center();
}
void Browser::OnCloseWindow(wxCloseEvent &evt) {
wxMessageDialog *dlg = new wxMessageDialog(NULL, wxT("Are you sure?"), wxT("Alert"),
wxYES_NO | wxICON_QUESTION);
int retVal = dlg->ShowModal();
if (retVal == wxNO)
evt.Veto();
else
evt.Skip(TRUE);
}
void Browser::OnNavigationComplete(wxWebViewEvent &evt) {
}
void Browser::OnDocumentLoaded(wxWebViewEvent &evt) {
m_web->RunScript("document.getElementById(\"suggestion-search\").value = \"The Matrix Revolutions\";");
m_web->RunScript("document.getElementById(\"suggestion-search-button\").click();");
}
main.h
#include <wx/wxprec.h>
#ifndef WX_PRECOMP
#include <wx/wx.h>
#endif // WX_PRECOMP
class MainApp:public wxApp {
public:
virtual bool OnInit();
};
wxIMPLEMENT_APP(MainApp);
main.cpp
#include "main.h"
#include "browser.h"
bool MainApp::OnInit() {
Browser *browser = new Browser(wxT("Browser Demo"));
browser->Show(true);
return TRUE;
}
The sample output is shown below:
Leave a Reply