Esempio n. 1
0
def scriptFromString(name, jsCode):
    script = QWebEngineScript()
    script.setName(name)
    script.setSourceCode(jsCode)
    script.setWorldId(QWebEngineScript.MainWorld)
    script.setInjectionPoint(QWebEngineScript.DocumentCreation)
    return script
    def setCSS(self):
        SCRIPT = """
var style = document.createElement('style');
style.innerHTML = `
._n3{
    margin: 0 !important;
    width: 100% !important;
    display: block !important;
}

._3_pc{
    left: 0 !important;
    max-width: none !important;
    min-width: none !important;
    width: 0 !important;
}

._3_pc._30u8{
    height: 100vh !important;
    max-width: none !important;
    min-width: 0 !important;
}
`;
document.head.appendChild(style);
        """

        #view.page().runJavaScript(SCRIPT, QWebEngineScript.ApplicationWorld)
        #inject script, run on document ready
        script = QWebEngineScript()
        script.setName("fullScreenGame")
        script.setSourceCode(SCRIPT)
        script.setInjectionPoint(QWebEngineScript.DocumentReady)
        #script.setRunsOnSubFrames(True)
        script.setWorldId(QWebEngineScript.ApplicationWorld)
        self.page().scripts().insert(script)
Esempio n. 3
0
 def __init__(self):
   super().__init__()
   self.init_ui()
   # 脚本
   self.profile = QWebEngineProfile.defaultProfile()
   self.script = QWebEngineScript()
   self.prepare_script()
def inject_userscripts():
    """Register user JavaScript files with the global profiles."""
    # The Greasemonkey metadata block support in QtWebEngine only starts at
    # Qt 5.8. With 5.7.1, we need to inject the scripts ourselves in response
    # to urlChanged.
    if not qtutils.version_check('5.8'):
        return

    # Since we are inserting scripts into profile.scripts they won't
    # just get replaced by new gm scripts like if we were injecting them
    # ourselves so we need to remove all gm scripts, while not removing
    # any other stuff that might have been added. Like the one for
    # stylesheets.
    greasemonkey = objreg.get('greasemonkey')
    for profile in [default_profile, private_profile]:
        scripts = profile.scripts()
        for script in scripts.toList():
            if script.name().startswith("GM-"):
                log.greasemonkey.debug('Removing script: {}'
                                       .format(script.name()))
                removed = scripts.remove(script)
                assert removed, script.name()

        # Then add the new scripts.
        for script in greasemonkey.all_scripts():
            # @run-at (and @include/@exclude/@match) is parsed by
            # QWebEngineScript.
            new_script = QWebEngineScript()
            new_script.setWorldId(QWebEngineScript.MainWorld)
            new_script.setSourceCode(script.code())
            new_script.setName("GM-{}".format(script.name))
            new_script.setRunsOnSubFrames(script.runs_on_sub_frames)
            log.greasemonkey.debug('adding script: {}'
                                   .format(new_script.name()))
            scripts.insert(new_script)
Esempio n. 5
0
 def scriptCreator(path, name, page):
     script = QWebEngineScript()
     f = open(path, 'r')
     script.setSourceCode(f.read())
     script.setInjectionPoint(QWebEngineScript.DocumentReady)
     script.setName(name)
     script.setWorldId(QWebEngineScript.MainWorld)
     page.scripts().insert(script)
Esempio n. 6
0
    def inject_script(self):
        script = QWebEngineScript()
        script.setSourceCode('''
            console.log("hi javascript!");

        ''')
        script.setWorldId(QWebEngineScript.MainWorld)
        script.setInjectionPoint(QWebEngineScript.DocumentReady)
        script.setRunsOnSubFrames(False)
        self.page().scripts().insert(script)
Esempio n. 7
0
 def webScript(self):
     """
     Public method to create a script object.
     
     @return prepared script object
     @rtype QWebEngineScript
     """
     script = QWebEngineScript()
     script.setSourceCode("{0}\n{1}".format(bootstrap_js, self.__script))
     script.setName(self.fullName())
     script.setWorldId(WebBrowserPage.SafeJsWorld)
     script.setRunsOnSubFrames(not self.__noFrames)
     return script
Esempio n. 8
0
    def _create_webengine_script(path: Url, name: str) -> QWebEngineScript:
        script = QWebEngineScript()
        script_file = QFile(path)

        if script_file.open(QFile.ReadOnly):
            script_string = str(script_file.readAll(), 'utf-8')

            script.setInjectionPoint(QWebEngineScript.DocumentCreation)
            script.setName(name)
            script.setWorldId(QWebEngineScript.MainWorld)
            script.setSourceCode(script_string)

        return script
Esempio n. 9
0
        def inject_js(filepath,
                      ipoint=QWebEngineScript.DocumentCreation,
                      iid=QWebEngineScript.ApplicationWorld,
                      sub_frames=False):
            f = QFile(filepath)
            assert f.open(QFile.ReadOnly | QFile.Text)
            src = QTextStream(f).readAll()

            script = QWebEngineScript()
            script.setInjectionPoint(ipoint)
            script.setSourceCode(src)
            script.setWorldId(iid)
            script.setRunsOnSubFrames(sub_frames)
            self.q_profile.scripts().insert(script)
Esempio n. 10
0
	def __init__(self):
		QWebEngineView.__init__(self)
		self.index = 0
		self.page().loadFinished.connect(self.loadFinished)
		self.page().loadProgress.connect(self.loadProgress)

		self.script = QWebEngineScript()
		self.script.setInjectionPoint(QWebEngineScript.Deferred)
		self.script.setRunsOnSubFrames(True)

		self.urlLogin = QUrl("http://reg.163.com/Logout.jsp?url=http://ecard.163.com/account/query_balance")
		self.urlVerify = QUrl("http://ecard.163.com/handle_login")
		self.urlBalance = QUrl("http://ecard.163.com/handle_query_verify")

		self.queryCallBack = None
		self.setProgress = None
Esempio n. 11
0
def create_profile():
    ans = getattr(create_profile, 'ans', None)
    if ans is None:
        ans = create_profile.ans = QWebEngineProfile(QApplication.instance())
        s = QWebEngineScript()
        s.setName('csslint.js')
        s.setSourceCode(csslint_js())
        s.setWorldId(QWebEngineScript.ApplicationWorld)
        ans.scripts().insert(s)
    return ans
Esempio n. 12
0
def ethereumClientScripts(connParams):
    scripts = []
    jsFile = QFile(':/share/js/web3.min.js')
    if not jsFile.open(QFile.ReadOnly):
        return None

    libCode = jsFile.readAll().data().decode('utf-8')
    libCode += "\n"

    if connParams.provType == 'http':
        libCode += w3ScriptHttp.format(rpcurl=connParams.rpcUrl)
    elif connParams.provType == 'websocket':
        libCode += w3ScriptWs.format(rpcurl=connParams.rpcUrl)

    scriptWeb3 = QWebEngineScript()
    scriptWeb3.setName('web3.js')
    scriptWeb3.setSourceCode(libCode)
    scriptWeb3.setWorldId(QWebEngineScript.MainWorld)
    scriptWeb3.setInjectionPoint(QWebEngineScript.DocumentCreation)
    scripts.append(scriptWeb3)
    return scripts
Esempio n. 13
0
 def set_scripts(self):
     script = QWebEngineScript()
     script.setInjectionPoint(QWebEngineScript.DocumentCreation)
     script.setWorldId(QWebEngineScript.MainWorld)
     script.setSourceCode("""(function() {
                                 var _old_alert = window.alert;
                                 window.alert = function() {
                                     document.activeElement.innerHTML += "<br>alerting";
                                     _old_alert.apply(window,arguments);
                                     document.activeElement.innerHTML += "<br>done alerting<br>";
                                 };
                             })();
                          """)
     self.webProfile.scripts().insert(script)
Esempio n. 14
0
    def _init_js(self):
        js_code = '\n'.join([
            '"use strict";',
            'window._qutebrowser = {};',
            utils.read_file('javascript/scroll.js'),
            utils.read_file('javascript/webelem.js'),
        ])
        script = QWebEngineScript()
        script.setInjectionPoint(QWebEngineScript.DocumentCreation)
        script.setSourceCode(js_code)

        page = self._widget.page()
        try:
            page.runJavaScript("", QWebEngineScript.ApplicationWorld)
        except TypeError:
            # We're unable to pass a world to runJavaScript
            script.setWorldId(QWebEngineScript.MainWorld)
        else:
            script.setWorldId(QWebEngineScript.ApplicationWorld)

        # FIXME:qtwebengine  what about runsOnSubFrames?
        page.scripts().insert(script)
Esempio n. 15
0
    def _init_js(self):
        js_code = '\n'.join([
            '"use strict";',
            'window._qutebrowser = window._qutebrowser || {};',
            utils.read_file('javascript/scroll.js'),
            utils.read_file('javascript/webelem.js'),
        ])
        script = QWebEngineScript()
        script.setInjectionPoint(QWebEngineScript.DocumentCreation)
        script.setSourceCode(js_code)

        page = self._widget.page()
        script.setWorldId(QWebEngineScript.ApplicationWorld)

        # FIXME:qtwebengine  what about runsOnSubFrames?
        page.scripts().insert(script)
Esempio n. 16
0
    def _init_js(self):
        js_code = '\n'.join([
            '"use strict";',
            'window._qutebrowser = {};',
            utils.read_file('javascript/scroll.js'),
            utils.read_file('javascript/webelem.js'),
        ])
        script = QWebEngineScript()
        script.setInjectionPoint(QWebEngineScript.DocumentCreation)
        script.setSourceCode(js_code)

        page = self._widget.page()
        try:
            page.runJavaScript("", QWebEngineScript.ApplicationWorld)
        except TypeError:
            # We're unable to pass a world to runJavaScript
            script.setWorldId(QWebEngineScript.MainWorld)
        else:
            script.setWorldId(QWebEngineScript.ApplicationWorld)

        # FIXME:qtwebengine  what about runsOnSubFrames?
        page.scripts().insert(script)
Esempio n. 17
0
    def execute_in_view(self, view: QWebEngineView):
        view.load(Core.QUrl(self.url))
        page = view.page()

        channel = QWebChannel(view)
        page.setWebChannel(channel)
        channel.registerObject('app_receiver', self.receiver)

        script = QWebEngineScript()
        script.setSourceCode(_get_jsinject_dep_code() + self.jscode)
        script.setWorldId(QWebEngineScript.MainWorld)
        page.profile().scripts().insert(script)
Esempio n. 18
0
    def _init_js(self):
        js_code = '\n'.join([
            '"use strict";',
            'window._qutebrowser = window._qutebrowser || {};',
            utils.read_file('javascript/scroll.js'),
            utils.read_file('javascript/webelem.js'),
            utils.read_file('javascript/caret.js'),
        ])
        script = QWebEngineScript()
        # We can't use DocumentCreation here as WORKAROUND for
        # https://bugreports.qt.io/browse/QTBUG-66011
        script.setInjectionPoint(QWebEngineScript.DocumentReady)
        script.setSourceCode(js_code)

        page = self._widget.page()
        script.setWorldId(QWebEngineScript.ApplicationWorld)

        # FIXME:qtwebengine  what about runsOnSubFrames?
        page.scripts().insert(script)
Esempio n. 19
0
    def _init_js(self):
        js_code = '\n'.join([
            '"use strict";',
            'window._qutebrowser = window._qutebrowser || {};',
            utils.read_file('javascript/scroll.js'),
            utils.read_file('javascript/webelem.js'),
            utils.read_file('javascript/caret.js'),
        ])
        script = QWebEngineScript()
        # We can't use DocumentCreation here as WORKAROUND for
        # https://bugreports.qt.io/browse/QTBUG-66011
        script.setInjectionPoint(QWebEngineScript.DocumentReady)
        script.setSourceCode(js_code)

        page = self._widget.page()
        script.setWorldId(QWebEngineScript.ApplicationWorld)

        # FIXME:qtwebengine  what about runsOnSubFrames?
        page.scripts().insert(script)
Esempio n. 20
0
 def _init_webchannel(self):
     wc_script = QWebEngineScript()
     wc_script.setInjectionPoint(QWebEngineScript.DocumentCreation)
     wc_script.setWorldId(QWebEngineScript.MainWorld)
     qwebchannel_js = QFile(":/qtwebchannel/qwebchannel.js")
     #qwebchannel_js = QFile("/tmp/qwebchannel.js")
     if qwebchannel_js.open(QIODevice.ReadOnly):
         js_src = bytes(qwebchannel_js.readAll()).decode('utf-8')
         ## XXX: Sometimes get Uncaught ReferenceError: qt is not defined
         #INFO: [:441] Attaching to qt.webChannelTransport
         #ERROR:[:442] Uncaught ReferenceError: qt is not defined
         js_src += """\n
                 console.log("Attaching to qt.webChannelTransport");
         new QWebChannel(qt.webChannelTransport, function(channel) {
                 console.log("MADE A NEW QUTEEEEE!!");
                   window.qute = channel.objects.qute; });"""
         wc_script.setSourceCode(js_src)
     else:
         wc_script = None
         log.greasemonkey.error('Failed to load qwebchannel.js with error: '
                                '%s' % qwebchannel_js.errorString())
     scripts = self._widget.page().scripts()
     if wc_script: scripts.insert(wc_script)
Esempio n. 21
0
def inject_userscripts():
    """Register user JavaScript files with the global profiles."""
    # The Greasemonkey metadata block support in QtWebEngine only starts at
    # Qt 5.8. With 5.7.1, we need to inject the scripts ourselves in response
    # to urlChanged.
    if not qtutils.version_check('5.8'):
        return

    # Since we are inserting scripts into profile.scripts they won't
    # just get replaced by new gm scripts like if we were injecting them
    # ourselves so we need to remove all gm scripts, while not removing
    # any other stuff that might have been added. Like the one for
    # stylesheets.
    greasemonkey = objreg.get('greasemonkey')
    for profile in [default_profile, private_profile]:
        scripts = profile.scripts()
        for script in scripts.toList():
            if script.name().startswith("GM-"):
                log.greasemonkey.debug('Removing script: {}'.format(
                    script.name()))
                removed = scripts.remove(script)
                assert removed, script.name()

        # Then add the new scripts.
        for script in greasemonkey.all_scripts():
            new_script = QWebEngineScript()
            new_script.setWorldId(QWebEngineScript.MainWorld)
            new_script.setSourceCode(script.code())
            new_script.setName("GM-{}".format(script.name))
            new_script.setRunsOnSubFrames(script.runs_on_sub_frames)
            log.greasemonkey.debug('adding script: {}'.format(
                new_script.name()))
            scripts.insert(new_script)
Esempio n. 22
0
def _init_stylesheet(profile):
    """Initialize custom stylesheets.

    Mostly inspired by QupZilla:
    https://github.com/QupZilla/qupzilla/blob/v2.0/src/lib/app/mainapplication.cpp#L1063-L1101
    https://github.com/QupZilla/qupzilla/blob/v2.0/src/lib/tools/scripts.cpp#L119-L132

    FIXME:qtwebengine Use QWebEngineStyleSheet once that's available
    https://codereview.qt-project.org/#/c/148671/
    """
    old_script = profile.scripts().findScript('_qute_stylesheet')
    if not old_script.isNull():
        profile.scripts().remove(old_script)

    css = shared.get_user_stylesheet()
    source = """
        (function() {{
            var css = document.createElement('style');
            css.setAttribute('type', 'text/css');
            css.appendChild(document.createTextNode('{}'));
            document.getElementsByTagName('head')[0].appendChild(css);
        }})()
    """.format(javascript.string_escape(css))

    script = QWebEngineScript()
    script.setName('_qute_stylesheet')
    script.setInjectionPoint(QWebEngineScript.DocumentReady)
    script.setWorldId(QWebEngineScript.ApplicationWorld)
    script.setRunsOnSubFrames(True)
    script.setSourceCode(source)
    profile.scripts().insert(script)
Esempio n. 23
0
def orbitScripts(connParams):
    scripts = []
    jsFile = QFile(':/share/js/orbit-db/orbitdb.js')
    if not jsFile.open(QFile.ReadOnly):
        return
    scriptJsIpfs = QWebEngineScript()
    scriptJsIpfs.setName('orbit-db')
    scriptJsIpfs.setSourceCode(jsFile.readAll().data().decode('utf-8'))
    scriptJsIpfs.setWorldId(QWebEngineScript.MainWorld)
    scriptJsIpfs.setInjectionPoint(QWebEngineScript.DocumentCreation)
    scriptJsIpfs.setRunsOnSubFrames(True)
    scripts.append(scriptJsIpfs)

    script = QWebEngineScript()
    script.setSourceCode('\n'.join([
        "document.addEventListener('DOMContentLoaded', function () {",
        "window.orbitdb = new OrbitDB(window.ipfs)", "})"
    ]))
    script.setWorldId(QWebEngineScript.MainWorld)
    return scripts
Esempio n. 24
0
    def _build_app(self):
        if self._inspector:
            os.environ.setdefault('QTWEBENGINE_REMOTE_DEBUGGING', '8001')

        # build webengine container
        self._lensview = lv = _QWebView(inspector=self._inspector)
        self._page = p = _QWebPage()
        lv.setPage(self._page)

        # connect to Qt signals
        lv.loadFinished.connect(self._loaded_cb)
        self._app.lastWindowClosed.connect(self._last_window_closed_cb)

        # build webchannel script and inject
        qwebchannel_js = QFile(':/qtwebchannel/qwebchannel.js')

        if not qwebchannel_js.open(QIODevice.ReadOnly):
            raise SystemExit('Failed to load qwebchannel.js with error: %s' % qwebchannel_js.errorString())

        qwebchannel_js = bytes(qwebchannel_js.readAll()).decode('utf-8')

        script = QWebEngineScript()
        script.setSourceCode(qwebchannel_js + '''
                window.lens = window.lens || {};
                window.lens._channel = new QWebChannel(qt.webChannelTransport, function(channel) {
                    window.lens.emit = function() {
                        var args = Array.prototype.slice.call(arguments);
                        if (args.length > 0) {
                            channel.objects.bridge._from_bridge(args);
                        }
                    };

                    channel.objects.bridge._emit_js_signal.connect(function(name, args) {
                        window.lens.__broadcast(name, args);
                    });
                });
            ''')
        script.setName('lens-bridge')
        script.setWorldId(QWebEngineScript.MainWorld)
        script.setInjectionPoint(QWebEngineScript.DocumentCreation)
        script.setRunsOnSubFrames(True)

        p.profile().scripts().insert(script)

        self._channel = QWebChannel(p)
        p.setWebChannel(self._channel)
        self._channel.registerObject('bridge', self)

        # set up scheme handlers for app:// and lens://
        self._app_scheme_handler = AppSchemeHandler()
        self._lens_scheme_handler = LensSchemeHandler()

        self._interceptor = RequestInterceptor()

        self._profile = QWebEngineProfile().defaultProfile()
        self._profile.installUrlSchemeHandler('app'.encode(), self._app_scheme_handler)
        self._profile.installUrlSchemeHandler('lens'.encode(), self._lens_scheme_handler)

        self._profile.setRequestInterceptor(self._interceptor)

        # connect to Lens signals
        self.on('__close_app', self._close_cb)

        # center on screen
        _frame_geometry = lv.frameGeometry()
        _active_screen = self._app.desktop().screenNumber(self._app.desktop().cursor().pos())
        _center = self._app.desktop().screenGeometry(_active_screen).center()
        _frame_geometry.moveCenter(_center)
        lv.move(_frame_geometry.topLeft())

        self.set_title(self._app_name)
        self.set_size(self._app_width, self._app_height)
Esempio n. 25
0
    def _initPreviewToTextSync(self):
        """Initialize the system per items 1, 2, and 4 above."""
        # When a web page finishes loading, reinsert our JavaScript.
        page = self._dock._widget.webEngineView.page()

        # Insert our scripts into every loaded page.
        qwebchannel_js = QFile(':/qtwebchannel/qwebchannel.js')
        if not qwebchannel_js.open(QIODevice.ReadOnly):
            raise SystemExit(
                'Failed to load qwebchannel.js with error: %s' %
                qwebchannel_js.errorString())
        qwebchannel_js = bytes(qwebchannel_js.readAll()).decode('utf-8')

        # Set up the QWebChannel. See http://doc.qt.io/qt-5/qtwebchannel-javascript.html.
        # Run the script containing QWebChannel.js first.
        beforeScript = QWebEngineScript()
        beforeScript.setSourceCode(qwebchannel_js + self._jsPreviewSync + self._qtJsInit)
        beforeScript.setName('qwebchannel.js, previewSync')
        # Run this JavaScript separated from any JavaScript present in the loaded web page. This provides better security (rogue pages can't access the QWebChannel) and better isolation (handlers, etc. won't conflict, I hope).
        beforeScript.setWorldId(QWebEngineScript.ApplicationWorld)
        beforeScript.setInjectionPoint(QWebEngineScript.DocumentCreation)
        # Per `setWebChannel <http://doc.qt.io/qt-5/qwebenginepage.html#setWebChannel>`_, only one channel is allowed per page. So, don't run this on sub-frames, since it will attempt the creation of more channels for each subframe.
        beforeScript.setRunsOnSubFrames(False)
        page.scripts().insert(beforeScript)

        # Set up the web channel. See https://riverbankcomputing.com/pipermail/pyqt/2015-August/036346.html
        # and http://stackoverflow.com/questions/28565254/how-to-use-qt-webengine-and-qwebchannel.
        # For debug, ``set QTWEBENGINE_REMOTE_DEBUGGING=port`` then browse to
        # http://127.0.0.1:port, where port=60000 works for me. See https://riverbankcomputing.com/pipermail/pyqt/2015-August/036346.html.
        self.channel = QWebChannel(page)
        self.channel.registerObject("previewSync", self)
        # Expose the ``qt.webChannelTransport`` object in the world where these scripts live.
        page.setWebChannel(self.channel, QWebEngineScript.ApplicationWorld)
Esempio n. 26
0
def ipfsClientScripts(connParams):
    scripts = []
    jsFile = QFile(':/share/js/ipfs-http-client/index.min.js')
    if not jsFile.open(QFile.ReadOnly):
        return

    scriptJsIpfs = QWebEngineScript()
    scriptJsIpfs.setName('ipfs-http-client')

    libCode = jsFile.readAll().data().decode('utf-8')
    libCode += "\n"
    libCode += ipfsInjScript.format(host=connParams.host,
                                    port=connParams.apiPort)

    scriptJsIpfs.setSourceCode(libCode)
    scriptJsIpfs.setWorldId(QWebEngineScript.MainWorld)
    scriptJsIpfs.setInjectionPoint(QWebEngineScript.DocumentCreation)
    scriptJsIpfs.setRunsOnSubFrames(True)
    scripts.append(scriptJsIpfs)
    return scripts
Esempio n. 27
0
 def create_script(src, name):
     s = QWebEngineScript()
     s.setName(name)
     s.setInjectionPoint(QWebEngineScript.DocumentReady)
     s.setWorldId(QWebEngineScript.ApplicationWorld)
     s.setRunsOnSubFrames(False)
     s.setSourceCode(src)
     return s
Esempio n. 28
0
 def getProfile(self):
     profile=QWebEngineProfile("myProfile")
     profile.cachePath="/home/yyk/Desktop/cache"
     jsFile = constants.QTWEBCHANNELJS_FILE
     with open(jsFile, encoding="UTF-8") as file:
         js = file.read()
     script = QWebEngineScript();
     script.setSourceCode(js)
     script.setName('qwebchannel.js')
     script.setInjectionPoint(QWebEngineScript.DocumentCreation)
     script.setWorldId(QWebEngineScript.MainWorld)
     script.setRunsOnSubFrames(False)
     profile.scripts().insert(script)
     return profile
Esempio n. 29
0
 def injectJS(self,sourceCode,name):
     script = QWebEngineScript();
     script.setSourceCode(sourceCode)
     script.setName(name)
     script.setInjectionPoint(QWebEngineScript.DocumentCreation)
     script.setWorldId(QWebEngineScript.MainWorld)
     script.setRunsOnSubFrames(True)
     self.view.page.scripts().insert(script)
     self.page.scripts().insert(script)
Esempio n. 30
0
class Browser(QWidget):
    def __init__(self):
        super().__init__()
        self.init_ui()

        # 脚本
        self.profile = QWebEngineProfile.defaultProfile()
        self.script = QWebEngineScript()
        self.prepare_script()

    def init_ui(self):
        self.webView = QWebEngineView()

        self.logEdit = QTextEdit()
        self.logEdit.setFixedHeight(100)

        self.addrEdit = QLineEdit()
        self.addrEdit.returnPressed.connect(self.load_url)
        self.webView.urlChanged.connect(
            lambda i: self.addrEdit.setText(i.toDisplayString()))

        self.jsEdit = QLineEdit()
        self.jsEdit.setText('inject.js')

        loadUrlBtn = QPushButton('加载')
        loadUrlBtn.clicked.connect(self.load_url)

        chooseJsBtn = QPushButton('选择脚本文件')
        chooseJsBtn.clicked.connect(self.choose_js_file)

        # 导航/工具
        top = QWidget()
        top.setFixedHeight(80)
        topBox = QVBoxLayout(top)
        topBox.setSpacing(0)
        topBox.setContentsMargins(5, 0, 0, 5)

        progBar = QProgressBar()
        progBox = QHBoxLayout()
        progBox.addWidget(progBar)
        topBox.addLayout(progBox)

        naviBox = QHBoxLayout()
        naviBox.addWidget(QLabel('网址'))
        naviBox.addWidget(self.addrEdit)
        naviBox.addWidget(loadUrlBtn)
        topBox.addLayout(naviBox)

        naviBox = QHBoxLayout()
        naviBox.addWidget(QLabel('注入脚本文件'))
        naviBox.addWidget(self.jsEdit)
        naviBox.addWidget(chooseJsBtn)
        topBox.addLayout(naviBox)

        self.webView.loadProgress.connect(progBar.setValue)

        # 主界面
        layout = QVBoxLayout(self)
        layout.addWidget(self.webView)
        layout.addWidget(top)
        layout.addWidget(self.logEdit)

        self.show()
        self.resize(1024, 900)
        self.center()

    def center(self):
        qr = self.frameGeometry()
        cp = QDesktopWidget().availableGeometry().center()
        qr.moveCenter(cp)
        self.move(qr.topLeft())

    @pyqtSlot()
    def load_url(self):
        url = self.addrEdit.text().strip()
        if not url.lower().startswith('http://') \
                and not url.lower().startswith('https://'):
            url = 'http://{}'.format(url)
        self.load(url)

    @pyqtSlot()
    def choose_js_file(self):
        f, _ = QFileDialog.getOpenFileName(filter="Javascript files(*.js)")
        if os.path.isfile(f):
            self.jsEdit.setText(f)
            self.prepare_script()

    def prepare_script(self):
        path = self.jsEdit.text().strip()
        if not os.path.isfile(path):
            self.log('invalid js path')
            return

        self.profile.scripts().remove(self.script)
        with open(path, 'r') as f:
            self.script.setSourceCode(f.read())
        self.profile.scripts().insert(self.script)
        self.log('injected js ready')

    def log(self, msg, *args, **kwargs):
        m = msg.format(*args, **kwargs)
        self.logEdit.append('{} {}'.format(datetime.now().strftime('%H:%M:%S'),
                                           m))

    def load(self, url):
        self.log(f'loading {url}')
        self.addrEdit.setText(url)
        self.webView.load(QUrl(url))
Esempio n. 31
0
 def _add_script(script, injection_point):
     new_script = QWebEngineScript()
     new_script.setInjectionPoint(injection_point)
     new_script.setWorldId(QWebEngineScript.MainWorld)
     new_script.setSourceCode(script.code())
     new_script.setName("GM-{}".format(script.name))
     new_script.setRunsOnSubFrames(script.runs_on_sub_frames)
     log.greasemonkey.debug("Adding script: {}"
                            .format(new_script.name()))
     scripts.insert(new_script)
Esempio n. 32
0
def _init_stylesheet(profile):
    """Initialize custom stylesheets.

    Partially inspired by QupZilla:
    https://github.com/QupZilla/qupzilla/blob/v2.0/src/lib/app/mainapplication.cpp#L1063-L1101
    """
    old_script = profile.scripts().findScript('_qute_stylesheet')
    if not old_script.isNull():
        profile.scripts().remove(old_script)

    css = shared.get_user_stylesheet()
    source = '\n'.join([
        '"use strict";',
        'window._qutebrowser = window._qutebrowser || {};',
        utils.read_file('javascript/stylesheet.js'),
        javascript.assemble('stylesheet', 'set_css', css),
    ])

    script = QWebEngineScript()
    script.setName('_qute_stylesheet')
    script.setInjectionPoint(QWebEngineScript.DocumentCreation)
    script.setWorldId(QWebEngineScript.ApplicationWorld)
    script.setRunsOnSubFrames(True)
    script.setSourceCode(source)
    profile.scripts().insert(script)
Esempio n. 33
0
def _init_stylesheet(profile):
    """Initialize custom stylesheets.

    Partially inspired by QupZilla:
    https://github.com/QupZilla/qupzilla/blob/v2.0/src/lib/app/mainapplication.cpp#L1063-L1101
    """
    old_script = profile.scripts().findScript('_qute_stylesheet')
    if not old_script.isNull():
        profile.scripts().remove(old_script)

    css = shared.get_user_stylesheet()
    source = '\n'.join([
        '"use strict";',
        'window._qutebrowser = window._qutebrowser || {};',
        utils.read_file('javascript/stylesheet.js'),
        javascript.assemble('stylesheet', 'set_css', css),
    ])

    script = QWebEngineScript()
    script.setName('_qute_stylesheet')
    script.setInjectionPoint(QWebEngineScript.DocumentCreation)
    script.setWorldId(QWebEngineScript.ApplicationWorld)
    script.setRunsOnSubFrames(True)
    script.setSourceCode(source)
    profile.scripts().insert(script)
Esempio n. 34
0
    def __init__(self):
        QWebEngineView.__init__(self)
        url = QDir().current().filePath(
            "html/QWebEngineView_07_print_request.html")
        url = QUrl.fromLocalFile(url)
        self.setUrl(url)
        web_channel_js = QWebEngineScript()
        web_channel_js.setInjectionPoint(QWebEngineScript.DocumentCreation)
        web_channel_js.setWorldId(QWebEngineScript.MainWorld)
        web_channel_js.setRunsOnSubFrames(True)
        web_channel_js_file = QFile(":/qwebchannel")
        web_channel_js_file.open(QFile.ReadOnly)
        js = str(web_channel_js_file.readAll(), 'utf-8')
        web_channel_js.setSourceCode(js)
        self.page().scripts().insert(web_channel_js)

        # Javascript window.print()를 오버라이드
        # 기본 window.print()는 웹브라우져에게 프린터 다이얼로그를 요청하지만
        # 받을 수 없기 때문에 QWebChannel을 통해 받는다.
        override_js_print = QWebEngineScript()
        override_js_print.setInjectionPoint(QWebEngineScript.DocumentCreation)
        override_js_print.setWorldId(QWebEngineScript.MainWorld)
        override_js_print.setName("oveerridejsprint.js")
        override_js_print.setRunsOnSubFrames(True)
        override_js_print.setSourceCode(
            "window.print = function() { "
            "   new QWebChannel(qt.webChannelTransport, function(channel) { "
            "       handler = channel.objects.handler; "
            "       handler.webToAppRequestPrint(); "
            "   });"
            "};")
        self.page().scripts().insert(override_js_print)
        channel = QWebChannel(self.page())
        self.page().setWebChannel(channel)
        self.handler = CallHandler()
        channel.registerObject('handler', self.handler)

        # 시그널슬롯 처리
        self.handler.request_print.connect(self.printer)
Esempio n. 35
0
    def _inject_early_js(self,
                         name,
                         js_code,
                         *,
                         world=QWebEngineScript.ApplicationWorld,
                         subframes=False):
        """Inject the given script to run early on a page load.

        This runs the script both on DocumentCreation and DocumentReady as on
        some internal pages, DocumentCreation will not work.

        That is a WORKAROUND for https://bugreports.qt.io/browse/QTBUG-66011
        """
        scripts = self._widget.page().scripts()
        for injection in ['creation', 'ready']:
            injection_points = {
                'creation': QWebEngineScript.DocumentCreation,
                'ready': QWebEngineScript.DocumentReady,
            }
            script = QWebEngineScript()
            script.setInjectionPoint(injection_points[injection])
            script.setSourceCode(js_code)
            script.setWorldId(world)
            script.setRunsOnSubFrames(subframes)
            script.setName('_qute_{}_{}'.format(name, injection))
            scripts.insert(script)
Esempio n. 36
0
 def _add_script(script, injection_point):
     new_script = QWebEngineScript()
     new_script.setInjectionPoint(injection_point)
     new_script.setWorldId(QWebEngineScript.MainWorld)
     new_script.setSourceCode(script.code())
     new_script.setName("GM-{}".format(script.name))
     new_script.setRunsOnSubFrames(script.runs_on_sub_frames)
     log.greasemonkey.debug("Adding script: {}".format(
         new_script.name()))
     scripts.insert(new_script)
def _init_stylesheet(profile):
    """Initialize custom stylesheets.

    Mostly inspired by QupZilla:
    https://github.com/QupZilla/qupzilla/blob/v2.0/src/lib/app/mainapplication.cpp#L1063-L1101
    https://github.com/QupZilla/qupzilla/blob/v2.0/src/lib/tools/scripts.cpp#L119-L132

    FIXME:qtwebengine Use QWebEngineStyleSheet once that's available
    https://codereview.qt-project.org/#/c/148671/
    """
    old_script = profile.scripts().findScript('_qute_stylesheet')
    if not old_script.isNull():
        profile.scripts().remove(old_script)

    css = shared.get_user_stylesheet()
    source = """
        (function() {{
            var css = document.createElement('style');
            css.setAttribute('type', 'text/css');
            css.appendChild(document.createTextNode('{}'));
            document.getElementsByTagName('head')[0].appendChild(css);
        }})()
    """.format(javascript.string_escape(css))

    script = QWebEngineScript()
    script.setName('_qute_stylesheet')
    script.setInjectionPoint(QWebEngineScript.DocumentReady)
    script.setWorldId(QWebEngineScript.ApplicationWorld)
    script.setRunsOnSubFrames(True)
    script.setSourceCode(source)
    profile.scripts().insert(script)
Esempio n. 38
0
 def runScript(self) -> None:
     # self.page().runJavaScript(navi_scripts, QWebEngineScript.ApplicationWorld)
     script = QWebEngineScript()
     script.setName("atcoder-optimizer")
     script.setSourceCode(navi_script)
     script.setInjectionPoint(QWebEngineScript.DocumentReady)
     script.setRunsOnSubFrames(True)
     script.setWorldId(QWebEngineScript.ApplicationWorld)
     self.page().scripts().insert(script)
Esempio n. 39
0
 def __init__(self):
     self.log = default_log
     self.current_frag = None
     self.com_id = unicode_type(uuid4())
     QWebEnginePage.__init__(self)
     secure_webengine(self.settings(), for_viewer=True)
     self.titleChanged.connect(self.title_changed)
     self.loadFinished.connect(self.show_frag)
     s = QWebEngineScript()
     s.setName('toc.js')
     s.setInjectionPoint(QWebEngineScript.InjectionPoint.DocumentReady)
     s.setRunsOnSubFrames(True)
     s.setWorldId(QWebEngineScript.ScriptWorldId.ApplicationWorld)
     s.setSourceCode(P('toc.js', allow_user_override=False, data=True).decode('utf-8').replace('COM_ID', self.com_id))
     self.scripts().insert(s)
    def authenticate_at(self, url, credentials):
        script_source = pkg_resources.resource_string(__name__,
                                                      "user.js").decode()
        script = QWebEngineScript()
        script.setInjectionPoint(QWebEngineScript.DocumentCreation)
        script.setWorldId(QWebEngineScript.ApplicationWorld)
        script.setSourceCode(script_source)
        self.page().scripts().insert(script)

        if credentials:
            logger.info("Initiating autologin", cred=credentials)
            for url_pattern, rules in self._auto_fill_rules.items():
                script = QWebEngineScript()
                script.setInjectionPoint(QWebEngineScript.DocumentReady)
                script.setWorldId(QWebEngineScript.ApplicationWorld)
                script.setSourceCode(f"""
// ==UserScript==
// @include {url_pattern}
// ==/UserScript==

function autoFill() {{
    {get_selectors(rules, credentials)}
    setTimeout(autoFill, 1000);
}}
autoFill();
""")
                self.page().scripts().insert(script)

        self.load(QUrl(url))