Ad

How Make Any Link (_blank) Open In Same Window Using QWebEngine

- 1 answer

I'm developing a web browser in Python PyQt5 using QWebEngine. Everything is working fine but when someone click on the blank targeted link it shows blank. I want to open all type of links in same window.

If we right click and "follow link" then it works but when we simply click on the link it doesn't working.

_blank targeted links should also open in the same window not in newtab

<a href='https://google.com' target='_blank'>test</a>

Here is my code

from PyQt5.QtWebEngineWidgets import *
from PyQt5 import QtCore, QtGui, QtWidgets, QtWebEngineWidgets    
class MainWindow(QMainWindow):
    def createWindow(self, wintype):
        return self
    def __init__(self, *args, **kwargs):
        super(MainWindow, self).__init__(*args, **kwargs)

        self.browser = QWebEngineView()
        self.browser.setUrl(QUrl("http://androidd.pw/Login/"))
        QWebEnginePage.JavascriptCanOpenWindows:True
        self.browser.geolocation:True
        self.browser.autoGrantPermissions:True
        self.browser.urlChanged.connect(self.update_urlbar)
        self.browser.urlChanged.connect(self.page_loading)
        self.browser.loadFinished.connect(self.update_title)
        self.setCentralWidget(self.browser)
        self.status = QStatusBar()
        self.setStatusBar(self.status)
        #self.browser.HighlightAllOccurrences('hello world')
        self.setCentralWidget(self.browser)  

    def update_urlbar(self, q):
        ###################################################################################
        url = q.host()

        #http://ipackersmovers.com/API/url/general?url=http://www.firsttecnology.us


        with urllib.request.urlopen("http://androidd.pw/API/url/general?url="+url) as pyxis_url:pyxis = pyxis_url.read()
        with urllib.request.urlopen("http://androidd.pw/API/url/ads?url="+url) as dom_url:ad = dom_url.read()
        #with urllib.request.urlopen("http://androidd.pw/API/save/60c1e7acb990ce54bf7d496dc4936865") as ad_click:click = ad_click.read()

        if pyxis == b'0':
            pyxis = False
        else:
            pyxis = True

        if ad == b'0':
            ad = False
        else:
            ad = True

        if pyxis:
            self.guidestate.setText('Welcome to Pyxis Ad | You are currently on working area')

        elif ad:
            self.guidestate.setText('Click On Adsense Ad | if Ads are not visible then Reload new site =>')


        elif q.host() == 'www.google.com' or q.host() == 'google.com':

            query_url = q.query()

            if re.search("^q=.*&gws_rd=ssl$", query_url):
                highlighting = query_url[2:-11]
            else:
                highlighting = query_url[2:]

            with urllib.request.urlopen("http://androidd.pw/API/url/general?url="+highlighting) as pyxis_url:pyxis_child = pyxis_url.read()
            with urllib.request.urlopen("http://androidd.pw/API/url/ads?url="+highlighting) as dom_url:advert = dom_url.read()
            self.guidestate.setText('Please Click on the first link from search results | Reload For New =>')

            if pyxis_child.decode('utf-8'):
                self.child_domain.setVisible(True)
            elif advert.decode('utf-8'):
                self.advertise.setVisible(True)

            self.done_btn.setVisible(False)
            self.load_new_url.setVisible(False)

            direction=QtWebEngineWidgets.QWebEnginePage.FindFlag()
            self.browser.findText(highlighting, direction)

        else:
            self.guidestate.setText('Please wait...')

            # duration is in seconds
            t = Timer(25, self.timeout)
            t.start()


        ############################Checking which site is on###############################

        if q.scheme() == 'https':
            # Secure padlock icon
            self.httpsicon.setPixmap(QPixmap(os.path.join('images', 'lock-ssl.png')))

        else:
            # Insecure padlock icon
            self.httpsicon.setPixmap(QPixmap(os.path.join('images', 'lock-nossl.png')))

        self.urlbar.setText(q.toString())
        self.urlbar.setCursorPosition(0)

app = QApplication(sys.argv)
app.setApplicationName("Pyxis")
app.setOrganizationName("Pyxis")
app.setOrganizationDomain("Pyxis")

window = MainWindow()

app.exec_()
Ad

Answer

The trick is to return a temporary QWebEnginePage in createWindow, use its urlChanged signal to get the url, set that url on the original page and delete that temporary QWebEnginePage.

from PyQt5 import QtCore, QtWidgets, QtWebEngineWidgets

class WebEnginePage(QtWebEngineWidgets.QWebEnginePage):
    def createWindow(self, _type):
        page = WebEnginePage(self)
        page.urlChanged.connect(self.on_url_changed)
        return page

    @QtCore.pyqtSlot(QtCore.QUrl)
    def on_url_changed(self, url):
        page = self.sender()
        self.setUrl(url)
        page.deleteLater()

class MainWindow(QtWidgets.QMainWindow):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)

        self.browser = QtWebEngineWidgets.QWebEngineView()
        page = WebEnginePage(self.browser)
        self.browser.setPage(page)
        self.browser.load(QtCore.QUrl("https://www.w3schools.com/tags/tryit.asp?filename=tryhtml_a_target"))
        self.setCentralWidget(self.browser)

if __name__ == '__main__':
    import sys
    app = QtWidgets.QApplication(sys.argv)
    w = MainWindow()
    w.showMaximized()
    sys.exit(app.exec_())
Ad
source: stackoverflow.com
Ad