コード例 #1
14
void CommandHandler::processCommand(const Command &command) const
{
    QWebEngineView *webView = ElectricWebView::instance()->webView();

    if (command.name() == "load") {
        if (command.arguments().isEmpty())
            webView->load(QUrl("about:blank"));
        else
            webView->load(QUrl(command.arguments().first()));
    } else if (command.name() == "stop") {
        webView->stop();
    } else if (command.name() == "reload") {
        webView->reload();
    } else if (command.name() == "back") {
        webView->back();
    } else if (command.name() == "forward") {
        webView->forward();
    } else if (command.name() == "open") {
        QString mode = command.arguments().value(0);

        if (mode == "maximized") {
            webView->showMaximized();
        } else if (mode == "fullscreen") {
            webView->setGeometry(qApp->desktop()->screenGeometry());
            webView->showFullScreen();
        }
    } else if (command.name() == "close") {
        webView->close();
    } else if (command.name() == "current_url") {
        command.sendResponse(webView->url().toString().toLocal8Bit());
    } else if (command.name() == "set_html") {
        QString type = command.arguments().value(0);
        QString value = command.arguments().mid(1, -1).join(' ');

        if (type == "string") {
            webView->page()->setHtml(value.toLocal8Bit());
        } else if (type == "file") {
            QFile file(value);
            file.open(QFile::ReadOnly);

            webView->page()->setHtml(file.readAll());
        }
    } else if (command.name() == "get_html") {
        QString format = command.arguments().value(0);

        QEventLoop loop;

        if (format == "html") {
            webView->page()->toHtml([&command, &loop](const QString &html) {
                if (!command.client().isNull()) {
                    command.sendResponse(QUrl::toPercentEncoding(html));

                    if (command.isGetter())
                        command.client()->close();
                }
                loop.quit();
            });
        } else if (format == "text") {
            webView->page()->toPlainText([&command, &loop](const QString &text) {
                if (!command.client().isNull()) {
                    command.sendResponse(QUrl::toPercentEncoding(text));

                    if (command.isGetter())
                        command.client()->close();
                }
                loop.quit();
            });
        } else {
            return;
        }

        loop.exec();
    } else if (command.name() == "current_title") {
        command.sendResponse(webView->title().toLocal8Bit());
    } else if (command.name() == "screenshot") {
        processScreenshotCommand(command);
    } else if (command.name() == "subscribe") {
        QString eventName = command.arguments().value(0);
        QStringList events = QStringList()
                << "title_changed"
                << "url_changed"
                << "load_started"
                << "load_finished"
                << "user_activity"
                << "info_message_raised"
                << "warning_message_raised"
                << "error_message_raised"
                << "feature_permission_requested";

        if (events.contains(eventName)) {
            Event event(command);
            event.setName(eventName);

            ElectricWebView::instance()->eventManager()->subscribe(event);
        }
    } else if (command.name() == "exec_js") {
        processJavaScriptCommand(command);
    } else if (command.name() == "inject_js") {
        QMap<QString, QWebEngineScript::ScriptWorldId> worlds;
        worlds["main"] = QWebEngineScript::MainWorld;
        worlds["application"] = QWebEngineScript::ApplicationWorld;
        worlds["user"] = QWebEngineScript::UserWorld;

        QMap<QString, QWebEngineScript::InjectionPoint> injectionPoints;
        injectionPoints["document_creation"] = QWebEngineScript::DocumentCreation;
        injectionPoints["document_ready"] = QWebEngineScript::DocumentReady;
        injectionPoints["deferred"] = QWebEngineScript::Deferred;

        QWebEngineScript::ScriptWorldId world = worlds[command.arguments().value(0)];
        QWebEngineScript::InjectionPoint injectionPoint = injectionPoints[command.arguments().value(1)];

        QWebEngineScript script;
        script.setWorldId(world);
        script.setInjectionPoint(injectionPoint);

        QString source = command.arguments().value(2);
        QString value = command.arguments().mid(3, -1).join(' ');

        if (source == "string") {
            script.setSourceCode(value);
        } else if (source == "file") {
            QFile file(value);
            file.open(QFile::ReadOnly);

            script.setSourceCode(file.readAll());
        }

        ElectricWebView::instance()->webView()->page()->scripts().insert(script);
    } else if (command.name() == "idle_time") {
        command.sendResponse(QString("%1").arg(ElectricWebView::instance()->inputEventFilter()->idle()).toLocal8Bit());
    } else if (command.name() == "block_user_activity") {
        bool block = QVariant(command.arguments().value(0)).toBool();
        ElectricWebView::instance()->inputEventFilter()->setBlock(block);
    } else if (command.name() == "exec_cmd") {
        bool sync = command.arguments().value(0) == "sync";

        if (sync) {
            QProcess *process = new QProcess;
            process->start(command.arguments().mid(1, -1).join(' '));
            process->waitForFinished(-1);
            command.sendResponse(QUrl::toPercentEncoding(process->readAllStandardOutput()));
        } else {
            QProcess::startDetached(command.arguments().mid(1, -1).join(' '));
        }
    } else if (command.name() == "accept_feature_request" || command.name() == "reject_feature_request") {
        QMap<QString, QWebEnginePage::Feature> features;
        features["geolocation"] = QWebEnginePage::Geolocation;
        features["audio_capture"] = QWebEnginePage::MediaAudioCapture;
        features["video_capture"] = QWebEnginePage::MediaVideoCapture;
        features["audio_video_capture"] = QWebEnginePage::MediaAudioVideoCapture;
        features["mouse_lock"] = QWebEnginePage::MouseLock;

        QUrl securityOrigin(command.arguments().value(1));
        QWebEnginePage::Feature feature = features[command.arguments().value(0)];
        QWebEnginePage::PermissionPolicy policy;

        if (command.name() == "accept_feature_request")
            policy = QWebEnginePage::PermissionGrantedByUser;
        else
            policy = QWebEnginePage::PermissionDeniedByUser;

        ElectricWebView::instance()->webView()->page()->setFeaturePermission(securityOrigin, feature, policy);
    } else if (command.name() == "quit") {
        int exitCode = command.arguments().value(0).toInt();
        qApp->exit(exitCode);
    }
}
コード例 #2
0
ファイル: gm_script.cpp プロジェクト: Acidburn0zzz/qupzilla
QWebEngineScript GM_Script::webScript() const
{
    QWebEngineScript::InjectionPoint injectionPoint;
    switch (startAt()) {
    case DocumentStart:
        injectionPoint = QWebEngineScript::DocumentCreation;
        break;
    case DocumentEnd:
        injectionPoint = QWebEngineScript::DocumentReady;
        break;
    case DocumentIdle:
        injectionPoint = QWebEngineScript::Deferred;
        break;
    default:
        Q_UNREACHABLE();
    }

    QWebEngineScript script;
    script.setName(fullName());
    script.setWorldId(QWebEngineScript::MainWorld);
    script.setInjectionPoint(injectionPoint);
    script.setRunsOnSubFrames(!m_noframes);
    script.setSourceCode(QSL("%1\n%2").arg(m_manager->bootstrapScript(), m_script));
    return script;
}
コード例 #3
0
void AutoScrollPlugin::updateScript()
{
    const QString name = QSL("_qupzilla_autoscroll");

    QWebEngineScript oldScript = mApp->webProfile()->scripts()->findScript(name);
    if (!oldScript.isNull()) {
        mApp->webProfile()->scripts()->remove(oldScript);
    }

    QWebEngineScript script;
    script.setName(name);
    script.setInjectionPoint(QWebEngineScript::DocumentCreation);
    script.setWorldId(QWebEngineScript::ApplicationWorld);
    script.setRunsOnSubFrames(false);

    QSettings settings(m_settingsPath + QL1S("/extensions.ini"), QSettings::IniFormat);
    settings.beginGroup(QSL("AutoScroll"));

    QString source = QzTools::readAllFileContents(QSL(":/autoscroll/data/autoscroll.js"));
    source.replace(QSL("%MOVE_SPEED%"), settings.value(QSL("Speed"), 5).toString());
    source.replace(QSL("%CTRL_CLICK%"), settings.value(QSL("CtrlClick"), true).toString());
    source.replace(QSL("%MIDDLE_CLICK%"), settings.value(QSL("MiddleClick"), true).toString());
    source.replace(QSL("%IMG_ALL%"), QzTools::pixmapToByteArray(QPixmap(QSL(":/autoscroll/data/scroll_all.png"))));
    source.replace(QSL("%IMG_HORIZONTAL%"), QzTools::pixmapToByteArray(QPixmap(QSL(":/autoscroll/data/scroll_horizontal.png"))));
    source.replace(QSL("%IMG_VERTICAL%"), QzTools::pixmapToByteArray(QPixmap(QSL(":/autoscroll/data/scroll_vertical.png"))));

    script.setSourceCode(source);

    mApp->webProfile()->scripts()->insert(script);
}
コード例 #4
0
NetworkAccessManager::NetworkAccessManager(QString id)
    : QNetworkAccessManager(0)
    , m_Id(id)
    , m_UserAgent(QString())
    , m_SslProtocol(QSsl::UnknownProtocol)
#ifdef WEBENGINEVIEW
    , m_Profile(new QWebEngineProfile(id))
#endif
{
#ifdef WEBENGINEVIEW
    if(Application::SaveSessionCookie())
        m_Profile->setPersistentCookiesPolicy(QWebEngineProfile::ForcePersistentCookies);
    else
        m_Profile->setPersistentCookiesPolicy(QWebEngineProfile::AllowPersistentCookies);

    m_Profile->setHttpAcceptLanguage(Application::GetAcceptLanguage());
#endif

#if defined(USE_WEBCHANNEL) || defined(PASSWORD_MANAGER) || QT_VERSION >= 0x050900
    static QString source;
    if(source.isEmpty()){
        QString inner;

#  ifdef USE_WEBCHANNEL
        inner += View::InstallWebChannelJsCode();
#  endif
#  ifdef PASSWORD_MANAGER
        inner += View::InstallSubmitEventJsCode();
#  endif
#  if defined WEBENGINEVIEW && QT_VERSION >= 0x050900
        static const QList<QEvent::Type> types =
            QList<QEvent::Type>() << QEvent::KeyPress << QEvent::KeyRelease;
        inner += View::InstallEventFilterJsCode(types);
#  endif
        source = QStringLiteral
            ("(function(){\n"
             "%1\n"
             "})();").arg(inner);
    }
#  ifdef WEBENGINEVIEW
    QWebEngineScript script;
    script.setInjectionPoint(QWebEngineScript::DocumentReady);
    script.setWorldId(QWebEngineScript::MainWorld);
    script.setRunsOnSubFrames(true);
    script.setSourceCode(source);
    m_Profile->scripts()->insert(script);
#  endif
#endif

#ifdef WEBENGINEVIEW
    connect(m_Profile, &QWebEngineProfile::downloadRequested,
            this, &NetworkAccessManager::HandleDownload);
#endif
    connect(this, &NetworkAccessManager::authenticationRequired,
            this, &NetworkAccessManager::HandleAuthentication);
#ifndef QT_NO_NETWORKPROXY
    connect(this, &NetworkAccessManager::proxyAuthenticationRequired,
            this, &NetworkAccessManager::HandleProxyAuthentication);
#endif
}
コード例 #5
0
void WebScrollBarManager::createUserScript(int thickness)
{
    QWebEngineScript script;
    script.setName(QSL("_kclient_scrollbar"));
    script.setInjectionPoint(QWebEngineScript::DocumentReady);
    script.setWorldId(WebPage::SafeJsWorld);
    script.setSourceCode(m_scrollbarJs.arg(thickness));
    mApp->webProfile()->scripts()->insert(script);
}
コード例 #6
0
ファイル: webview.cpp プロジェクト: zhipeng515/VRSteam
void WebView::insertJavaScript(QWebEngineScriptCollection *scripts)
{
    QFile webChannelFile(":/js/qwebchannel.js");
    webChannelFile.open(QIODevice::ReadOnly);
    QWebEngineScript webChannelScript;
    webChannelScript.setSourceCode(webChannelFile.readAll());
    webChannelScript.setInjectionPoint(QWebEngineScript::DocumentCreation);
    webChannelScript.setWorldId(QWebEngineScript::MainWorld);
    scripts->insert(webChannelScript);
}
コード例 #7
0
QWebEngineProfile* createWebEngineProfile(const WizWebEngineViewInjectObjects& objects, QObject* parent)
{
    if (objects.empty())
        return nullptr;
    //
    QWebEngineProfile *profile = new QWebEngineProfile("WizNoteWebEngineProfile", parent);
    //
    QString jsWebChannelFileName = Utils::WizPathResolve::resourcesPath() + "files/webengine/wizwebchannel.js";
    QString jsWebChannel;
    WizLoadUnicodeTextFromFile(jsWebChannelFileName, jsWebChannel);
    //
    QString initFileName = Utils::WizPathResolve::resourcesPath() + "files/webengine/wizwebengineviewinit.js";
    QString jsInit;
    WizLoadUnicodeTextFromFile(initFileName, jsInit);
    //
    CWizStdStringArray names;
    for (auto inject : objects) {
        names.push_back("\"" + inject.name + "\"");
    }
    //
    CString objectNames;
    WizStringArrayToText(names, objectNames, ", ");
    //
    jsInit.replace("__objectNames__", objectNames);
    //
    QString jsAll = jsWebChannel + "\n" + jsInit;
    //
    {
        QWebEngineScript script;
        script.setSourceCode(jsAll);
        script.setName("qwebchannel.js");
        script.setWorldId(QWebEngineScript::MainWorld);
        script.setInjectionPoint(QWebEngineScript::DocumentCreation);
        script.setRunsOnSubFrames(true);
        profile->scripts()->insert(script);
    }
    //
    return profile;
}
コード例 #8
0
bool QtWebEnginePage::acceptNavigationRequest(const QUrl &url, QWebEnginePage::NavigationType type, bool isMainFrame)
{
	if (m_isPopup)
	{
		emit aboutToNavigate(url, type);

		return false;
	}

	if (isMainFrame && url.scheme() == QLatin1String("javascript"))
	{
		runJavaScript(url.path());

		return false;
	}

	if (url.scheme() == QLatin1String("mailto"))
	{
		QDesktopServices::openUrl(url);

		return false;
	}

	if (isMainFrame && type == QWebEnginePage::NavigationTypeReload && m_previousNavigationType == QWebEnginePage::NavigationTypeFormSubmitted && SettingsManager::getValue(QLatin1String("Choices/WarnFormResend")).toBool())
	{
		bool cancel(false);
		bool warn(true);

		if (m_widget)
		{
			ContentsDialog dialog(ThemesManager::getIcon(QLatin1String("dialog-warning")), tr("Question"), tr("Are you sure that you want to send form data again?"), tr("Do you want to resend data?"), (QDialogButtonBox::Yes | QDialogButtonBox::Cancel), NULL, m_widget);
			dialog.setCheckBox(tr("Do not show this message again"), false);

			connect(m_widget, SIGNAL(aboutToReload()), &dialog, SLOT(close()));

			m_widget->showDialog(&dialog);

			cancel = !dialog.isAccepted();
			warn = !dialog.getCheckBoxState();
		}
		else
		{
			QMessageBox dialog;
			dialog.setWindowTitle(tr("Question"));
			dialog.setText(tr("Are you sure that you want to send form data again?"));
			dialog.setInformativeText(tr("Do you want to resend data?"));
			dialog.setIcon(QMessageBox::Question);
			dialog.setStandardButtons(QMessageBox::Yes | QMessageBox::Cancel);
			dialog.setDefaultButton(QMessageBox::Cancel);
			dialog.setCheckBox(new QCheckBox(tr("Do not show this message again")));

			cancel = (dialog.exec() == QMessageBox::Cancel);
			warn = !dialog.checkBox()->isChecked();
		}

		SettingsManager::setValue(QLatin1String("Choices/WarnFormResend"), warn);

		if (cancel)
		{
			return false;
		}
	}

	if (isMainFrame && type != QWebEnginePage::NavigationTypeReload)
	{
		m_previousNavigationType = type;
	}

	if (isMainFrame)
	{
		scripts().clear();

		const QList<UserScript*> scripts(AddonsManager::getUserScriptsForUrl(url));

		for (int i = 0; i < scripts.count(); ++i)
		{
			QWebEngineScript::InjectionPoint injectionPoint(QWebEngineScript::DocumentReady);

			if (scripts.at(i)->getInjectionTime() == UserScript::DocumentCreationTime)
			{
				injectionPoint = QWebEngineScript::DocumentCreation;
			}
			else if (scripts.at(i)->getInjectionTime() == UserScript::DeferredTime)
			{
				injectionPoint = QWebEngineScript::Deferred;
			}

			QWebEngineScript script;
			script.setSourceCode(scripts.at(i)->getSource());
			script.setRunsOnSubFrames(scripts.at(i)->shouldRunOnSubFrames());
			script.setInjectionPoint(injectionPoint);

			this->scripts().insert(script);
		}

		emit aboutToNavigate(url, type);
	}

	return true;
}