예제 #1
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():
            # @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)
예제 #2
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)
    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))
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)
예제 #5
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)
예제 #6
0
    def __init__(self, parent=None):
        """
        Constructor
        
        @param parent reference to the parent object (QObject)
        """
        super(PasswordManager, self).__init__(parent)

        # setup userscript to monitor forms
        script = QWebEngineScript()
        script.setName("_eric_passwordmonitor")
        script.setInjectionPoint(QWebEngineScript.DocumentReady)
        script.setWorldId(WebBrowserPage.SafeJsWorld)
        script.setRunsOnSubFrames(True)
        script.setSourceCode(Scripts.setupFormObserver())
        profile = WebBrowser.WebBrowserWindow.WebBrowserWindow.webProfile()
        profile.scripts().insert(script)

        self.__logins = {}
        self.__loginForms = {}
        self.__never = []
        self.__loaded = False
        self.__saveTimer = AutoSaver(self, self.save)

        self.changed.connect(self.__saveTimer.changeOccurred)
예제 #7
0
def _createWebengineScript(path: Url,
                           name: str,
                           injectionPoint=None,
                           isStylesheet: bool = False) -> QWebEngineScript:

    if injectionPoint is None:
        injectionPoint = QWebEngineScript.DocumentCreation

    script = QWebEngineScript()
    script_file = QFile(path)

    if script_file.open(QFile.ReadOnly):
        script_string = str(script_file.readAll(), 'utf-8')
        script.setInjectionPoint(injectionPoint)
        script.setName(name)
        script.setRunsOnSubFrames(True)
        script.setWorldId(QWebEngineScript.MainWorld)
        if isStylesheet:
            source = ("(function(){"
                      ""
                      "const css = document.createElement('style');\n"
                      "css.type = 'text/css';\n"
                      "css.innerText = `" + script_string.strip() + "`\n"
                      "document.head.appendChild(css);\n"
                      "})()")
            script.setSourceCode(source)
        else:
            script.setSourceCode(script_string)

    return script
예제 #8
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)
예제 #9
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)
예제 #10
0
def client_script():
    """ Reads qtwebchannel.js from disk and creates QWebEngineScript to inject to QT window.
        This allows for JavaScript code to call python methods marked by pyqtSlot in registered objects.

    Args:
        None.

    Returns:
        None.

    Raises:
    """
    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)
    script.setName('qWebChannelJS')
    script.setWorldId(QWebEngineScript.MainWorld)
    script.setInjectionPoint(QWebEngineScript.DocumentReady)
    script.setRunsOnSubFrames(True)
    return script
예제 #11
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)
예제 #12
0
def scriptFromString(name, jsCode):
    script = QWebEngineScript()
    script.setName(name)
    script.setSourceCode(jsCode)
    script.setWorldId(QWebEngineScript.MainWorld)
    script.setInjectionPoint(QWebEngineScript.DocumentCreation)
    return script
예제 #13
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)
    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)
예제 #15
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)
    def load_css(self, path, name):
        path = QFile(path)
        if not path.open(QFile.ReadOnly | QtCore.QFile.Text):
            return
        css = path.readAll().data().decode("utf-8")
        SCRIPT = """
        (function() {
        try {
        css = document.createElement('style');
        css.type = 'text/css';
        css.id = "%s";
        document.head.appendChild(css);
        css.innerText = `%s`;
        } catch(e) {}
        })()
        """ % (name, css)

        script = QWebEngineScript()
        self.web_page.runJavaScript(SCRIPT, QWebEngineScript.ApplicationWorld)
        script.setName(name)
        script.setSourceCode(SCRIPT)
        script.setInjectionPoint(QWebEngineScript.DocumentReady)
        script.setRunsOnSubFrames(True)
        script.setWorldId(QWebEngineScript.ApplicationWorld)
        self.web_page.scripts().insert(script)
예제 #17
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
예제 #18
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)
예제 #19
0
 def injectJs(self, source, name):
     js = QWebEngineScript()
     js.setName(name)
     js.setSourceCode(source)
     js.setInjectionPoint(QWebEngineScript.DocumentCreation)
     js.setWorldId(QWebEngineScript.MainWorld)
     js.setRunsOnSubFrames(True)
     self.scripts().insert(js)
예제 #20
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)
예제 #21
0
파일: test.py 프로젝트: yyk123/XwareDesktop
 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)
예제 #22
0
파일: test.py 프로젝트: yyk123/XwareDesktop
 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)
예제 #23
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)
예제 #24
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)
예제 #25
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)
예제 #26
0
def create_script(name, src, world=QWebEngineScript.ApplicationWorld, injection_point=QWebEngineScript.DocumentReady, on_subframes=True):
    script = QWebEngineScript()
    if isinstance(src, bytes):
        src = src.decode('utf-8')
    script.setSourceCode(src)
    script.setName(name)
    script.setWorldId(world)
    script.setInjectionPoint(injection_point)
    script.setRunsOnSubFrames(on_subframes)
    return script
예제 #27
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
예제 #28
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)
예제 #29
0
 def _onloadJS(self,
               code,
               name='',
               injection_point=QWebEngineScript.DocumentReady):
     script = QWebEngineScript()
     script.setName(name or ('script_' + str(random())[2:]))
     script.setSourceCode(code)
     script.setInjectionPoint(injection_point)
     script.setWorldId(script.MainWorld)
     script.setRunsOnSubFrames(False)
     self.page().scripts().insert(script)
     self.loadStarted.connect(lambda: self.page().scripts().insert(script))
예제 #30
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
예제 #31
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
예제 #32
0
    def inject(page, options: dict) -> None:
        if bindings() == "PyQt5":
            from PyQt5.QtWebEngineWidgets import QWebEngineScript
        else:
            from PySide2.QtWebEngineWidgets import QWebEngineScript

        script = QWebEngineScript()
        script.setName(options["name"])
        script.setWorldId(QWebEngineScript.MainWorld)
        script.setInjectionPoint(QWebEngineScript.DocumentCreation)
        script.setRunsOnSubFrames(True)
        script.setSourceCode(options["JavaScript"])
        print(f"Injecting JavaScript {options['name']}")
        page.profile().scripts().insert(script)
예제 #33
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)
예제 #34
0
파일: test.py 프로젝트: yyk123/XwareDesktop
 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
예제 #35
0
    def setupUserScripts(self):
        # WebChannel for SafeJsWorld
        script = QWebEngineScript()
        script.setName('_app_webchannel')
        script.setInjectionPoint(QWebEngineScript.DocumentCreation)
        script.setWorldId(WebPage.SafeJsWorld)
        script.setRunsOnSubFrames(True)
        script.setSourceCode(Scripts.setupWebChannel())
        self._webProfile.scripts().insert(script)

        # app:restore
        appRestore = QWebEngineScript()
        appRestore.setWorldId(WebPage.SafeJsWorld)
        appRestore.setSourceCode(
            gVar.appTools.readAllFileContents(':html/restore.user.js'))
        self._webProfile.scripts().insert(appRestore)

        # app:speeddial
        appSpeedDial = QWebEngineScript()
        appSpeedDial.setWorldId(WebPage.SafeJsWorld)
        appSpeedDial.setSourceCode(Scripts.setupSpeedDial())
        self._webProfile.scripts().insert(appSpeedDial)

        # document.window object addons
        documentWindowAddons = QWebEngineScript()
        documentWindowAddons.setName('_app_window_object')
        documentWindowAddons.setInjectionPoint(
            QWebEngineScript.DocumentCreation)
        documentWindowAddons.setWorldId(WebPage.UnsafeJsWorld)
        documentWindowAddons.setRunsOnSubFrames(True)
        documentWindowAddons.setSourceCode(Scripts.setupWindowObject())
        self._webProfile.scripts().insert(documentWindowAddons)
예제 #36
0
파일: test.py 프로젝트: yyk123/XwareDesktop
 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
예제 #37
0
파일: njaxt.py 프로젝트: ujjwal96/njaXt
 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)
예제 #38
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()
        script.setWorldId(QWebEngineScript.ApplicationWorld)

        # FIXME:qtwebengine  what about runsOnSubFrames?
        page.scripts().insert(script)
예제 #39
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)
예제 #40
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)
        page = self._widget.page()
        script.setSourceCode(js_code)

        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)
예제 #41
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)