Ejemplo n.º 1
0
        public static Tab CreateNewTab(WebView2Browser parentBrowser, WebView2Environment environment, int id, bool shouldBeActive)
        {
            Tab tab = new Tab(parentBrowser, environment, id, shouldBeActive);

            return(tab);
        }
Ejemplo n.º 2
0
        public void HandleTabMessageReceived(int tabId, Tab webview, WebMessageReceivedEventArgs eventArgs)
        {
            string jsonString = eventArgs.WebMessageAsJson;

            JObject jsonObj = JObject.Parse(jsonString);

            string uri = webview.Source;

            Messages message;

            if (!Enum.TryParse <Messages>(jsonObj["message"].Value <string>(), out message))
            {
                return;
            }

            JToken args = jsonObj["args"];

            switch (message)
            {
            case Messages.MG_GET_FAVORITES:
            case Messages.MG_REMOVE_FAVORITE:
            {
                string fileURI = GetFilePathAsURI(GetFullPathFor("Content\\content_ui\\favorites.html"));
                // Only the favorites UI can request favorites
                if (fileURI == uri)
                {
                    args["tabId"] = tabId;
                    PostJsonToWebView(jsonObj, controlsWebView2);
                }
            }
            break;

            case Messages.MG_GET_SETTINGS:
            {
                string fileURI = GetFilePathAsURI(GetFullPathFor("Content\\content_ui\\settings.html"));
                // Only the settings UI can request settings
                if (fileURI == uri)
                {
                    args["tabId"] = tabId;
                    PostJsonToWebView(jsonObj, controlsWebView2);
                }
            }
            break;

            case Messages.MG_CLEAR_CACHE:
            {
                string fileURI = GetFilePathAsURI(GetFullPathFor("Content\\content_ui\\settings.html"));
                // Only the settings UI can request cache clearing
                if (fileURI == uri)
                {
                    args["content"]  = false;
                    args["controls"] = false;

                    if (ClearContentCache())
                    {
                        args["content"] = true;
                    }

                    if (ClearControlsCache())
                    {
                        args["controls"] = true;
                    }

                    PostJsonToWebView(jsonObj, _tabDictionary[tabId]);
                }
            }
            break;

            case Messages.MG_CLEAR_COOKIES:
            {
                string fileURI = GetFilePathAsURI(GetFullPathFor("Content\\content_ui\\settings.html"));
                // Only the settings UI can request cookies clearing
                if (fileURI == uri)
                {
                    args["content"]  = false;
                    args["controls"] = false;

                    if (ClearContentCookies())
                    {
                        args["content"] = true;
                    }

                    if (ClearControlsCookies())
                    {
                        args["controls"] = true;
                    }

                    PostJsonToWebView(jsonObj, _tabDictionary[tabId]);
                }
            }
            break;

            case Messages.MG_GET_HISTORY:
            case Messages.MG_REMOVE_HISTORY_ITEM:
            case Messages.MG_CLEAR_HISTORY:
            {
                string fileURI = GetFilePathAsURI(GetFullPathFor("Content\\content_ui\\history.html"));
                // Only the history UI can request history
                if (fileURI == uri)
                {
                    args["tabId"] = tabId;
                    PostJsonToWebView(jsonObj, controlsWebView2);
                }
            }
            break;

            default:
            {
                //OutputDebugString(L"Unexpected message\n");
            }
            break;
            }
        }
Ejemplo n.º 3
0
        public void OnWebMessageRecieved(WebMessageReceivedEventArgs args)
        {
            string source = args.Source;
            string json   = args.WebMessageAsJson;
            string str    = args.WebMessageAsString;

            JObject jsonObj = JObject.Parse(json);

            if (!jsonObj.ContainsKey("message"))
            {
                return;
            }

            if (!jsonObj.ContainsKey("args"))
            {
                return;
            }


            Messages m;

            if (!Enum.TryParse <Messages>(jsonObj["message"].Value <string>(), out m))
            {
                return;
            }
            JToken msgArgs = jsonObj["args"];

            switch (m)
            {
            case Messages.MG_CREATE_TAB:
            {
                int  tabId          = msgArgs["tabId"].Value <int>();
                bool shouldBeActive = msgArgs["active"].Value <bool>();

                Tab newTab = Tab.CreateNewTab(this, _contentEnvironment, tabId, shouldBeActive);

                if (!_tabDictionary.ContainsKey(tabId))
                {
                    newTab.Dock = DockStyle.Fill;
                    tableLayoutPanel1.Controls.Add(newTab, 0, 1);

                    _tabDictionary.Add(tabId, newTab);
                }
            }
            break;

            case Messages.MG_NAVIGATE:
            {
                string uri           = msgArgs["uri"].Value <string>();
                string browserScheme = "browser://";

                if (uri.Contains(browserScheme))
                {
                    string path = uri.Substring(browserScheme.Length);
                    if (path == "favorites" ||
                        path == "settings" ||
                        path == "history")
                    {
                        string filePath = "Content\\content_ui\\";
                        filePath  = Path.Combine(filePath, path);
                        filePath += ".html";
                        string fullPath = GetFullPathFor(filePath);
                        _tabDictionary[_activeTabId].Navigate(fullPath);
                    }
                    else
                    {
                        System.Diagnostics.Debug.WriteLine("Requested unknown browser page");
                    }
                }
                else
                {
                    _tabDictionary[_activeTabId].Navigate(uri);
                }
            }
            break;

            case Messages.MG_GO_FORWARD:
            {
                _tabDictionary[_activeTabId].GoForward();
            }
            break;

            case Messages.MG_GO_BACK:
            {
                _tabDictionary[_activeTabId].GoBack();
            }
            break;

            case Messages.MG_RELOAD:
            {
                _tabDictionary[_activeTabId].Reload();
            }
            break;

            case Messages.MG_CANCEL:
            {
                _tabDictionary[_activeTabId].CallDevToolsProtocolMethod("Page.stopLoading", "{}", null);
            }
            break;

            case Messages.MG_SWITCH_TAB:
            {
                int tabId = msgArgs["tabId"].Value <int>();

                SwitchToTab(tabId);
            }
            break;

            case Messages.MG_CLOSE_TAB:
            {
                int tabId = msgArgs["tabId"].Value <int>();
                tableLayoutPanel1.Controls.Remove(_tabDictionary[tabId]);
                _tabDictionary.Remove(tabId);
            }
            break;

            case Messages.MG_CLOSE_WINDOW:
            {
                Close();
            }
            break;

            case Messages.MG_SHOW_OPTIONS:
            {
                _optionsWebView.Visible = true;
                ResizeUIWebViews();
                _optionsWebView.BringToFront();
                _optionsWebView.Focus();
            }
            break;

            case Messages.MG_HIDE_OPTIONS:
            {
                _optionsWebView.Visible = false;
            }
            break;

            case Messages.MG_OPTION_SELECTED:
            {
                _tabDictionary[_activeTabId].Focus();
            }
            break;

            case Messages.MG_GET_FAVORITES:
            case Messages.MG_GET_SETTINGS:
            case Messages.MG_GET_HISTORY:
            {
                // Forward back to requesting tab
                JToken tabIdToken = msgArgs["tabId"];
                int    tabId      = tabIdToken.Value <int>();

                RemoveFields(msgArgs, new string[] { "tabId" });

                PostJsonToWebView(jsonObj, _tabDictionary[tabId]);
            }
            break;
            }
        }
Ejemplo n.º 4
0
        public void HandleTabNavCompleted(int tabId, Tab webview, bool isSuccess)
        {
            string getTitleScript =
                // Look for a title tag
                "(() => {" +
                "    const titleTag = document.getElementsByTagName('title')[0];" +
                "    if (titleTag) {" +
                "        return titleTag.innerHTML;" +
                "    }" +
                // No title tag, look for the file name
                "    pathname = window.location.pathname;" +
                "    var filename = pathname.split('/').pop();" +
                "    if (filename) {" +
                "        return filename;" +
                "    }" +
                // No file name, look for the hostname
                "    const hostname =  window.location.hostname;" +
                "    if (hostname) {" +
                "        return hostname;" +
                "    }" +
                // Fallback: let the UI use a generic title
                "    return '';" +
                "})();";

            string getFaviconURI =
                "(() => {" +
                // Let the UI use a fallback favicon
                "    let faviconURI = '';" +
                "    let links = document.getElementsByTagName('link');" +
                // Test each link for a favicon
                "    Array.from(links).map(element => {" +
                "        let rel = element.rel;" +
                // Favicon is declared, try to get the href
                "        if (rel && (rel == 'shortcut icon' || rel == 'icon')) {" +
                "            if (!element.href) {" +
                "                return;" +
                "            }" +
                // href to icon found, check it's full URI
                "            try {" +
                "                let urlParser = new URL(element.href);" +
                "                faviconURI = urlParser.href;" +
                "            } catch(e) {" +
                // Try prepending origin
                "                let origin = window.location.origin;" +
                "                let faviconLocation = `${origin}/${element.href}`;" +
                "                try {" +
                "                    urlParser = new URL(faviconLocation);" +
                "                    faviconURI = urlParser.href;" +
                "                } catch (e2) {" +
                "                    return;" +
                "                }" +
                "            }" +
                "        }" +
                "    });" +
                "    return faviconURI;" +
                "})();";

            webview.ExecuteScript(getTitleScript, (ExecuteScriptCompletedEventArgs args) =>
            {
                if (args.ErrorCode != 0)
                {
                    return;
                }

                StringBuilder titleSb = new StringBuilder();
                StringWriter titleSw  = new StringWriter(titleSb);

                using (JsonWriter writer = new JsonTextWriter(titleSw))
                {
                    writer.Formatting = Formatting.Indented;

                    writer.WriteStartObject();
                    writer.WritePropertyName("message");
                    writer.WriteValue(Messages.MG_UPDATE_TAB);
                    writer.WritePropertyName("args");
                    writer.WriteStartObject();
                    writer.WritePropertyName("title");
                    writer.WriteValue(args.ResultAsJson.Trim('"'));
                    writer.WritePropertyName("tabId");
                    writer.WriteValue(tabId);
                }
                string titleJson = titleSb.ToString();

                PostJsonToWebView(titleJson, controlsWebView2);
            });


            webview.ExecuteScript(getFaviconURI, (ExecuteScriptCompletedEventArgs args) =>
            {
                if (args.ErrorCode != 0)
                {
                    return;
                }
                StringBuilder iconSb = new StringBuilder();
                StringWriter iconSw  = new StringWriter(iconSb);

                using (JsonWriter writer = new JsonTextWriter(iconSw))
                {
                    writer.Formatting = Formatting.Indented;

                    writer.WriteStartObject();
                    writer.WritePropertyName("message");
                    writer.WriteValue(Messages.MG_UPDATE_FAVICON);
                    writer.WritePropertyName("args");
                    writer.WriteStartObject();
                    writer.WritePropertyName("uri");
                    writer.WriteValue(args.ResultAsJson);
                    writer.WritePropertyName("tabId");
                    writer.WriteValue(tabId);
                }
                string iconJson = iconSw.ToString();

                PostJsonToWebView(iconJson, controlsWebView2);
            });


            StringBuilder sb = new StringBuilder();
            StringWriter  sw = new StringWriter(sb);

            using (JsonWriter writer = new JsonTextWriter(sw))
            {
                writer.Formatting = Formatting.Indented;

                writer.WriteStartObject();
                writer.WritePropertyName("message");
                writer.WriteValue(Messages.MG_NAV_COMPLETED);
                writer.WritePropertyName("args");
                writer.WriteStartObject();
                writer.WritePropertyName("tabId");
                writer.WriteValue(tabId);
                writer.WritePropertyName("isError");
                writer.WriteValue(!isSuccess);
            }

            string json = sw.ToString();

            PostJsonToWebView(json, controlsWebView2);
        }