Techrex Studios
Techrex Studios

Reputation: 102

How to open a specific URL (a YouTube video) on a button click in UWP C#?

EDIT: I was just checking if the entire Tag was blank, instead of the URL in the tag, so it resulted in being always blank and always throwing exceptions.

I want to be able to open a specific URL on a button click, like a YouTube video, google search etc. in the user's default browser

When using await Windows.System.Launcher.LaunchUriAsync(new Uri(url)); the URLs are invalid and this method only opens 'normal' websites, like https://microsoft.com.

Is there any way to open a specific URL on a button click?

The code:

private async void imageTapEvent(object sender, RoutedEventArgs e)
    {
        try
        {
            if (((String)(((Image)sender).Tag)) != "")
                await Windows.System.Launcher.LaunchUriAsync(new Uri(((ImageTag)(((Image)sender).Tag)).url));
        }
        catch (Exception)
        {
            MessageDialog msg = new MessageDialog("The chosen URL is invalid", "Invalid URL");
            await msg.ShowAsync();
    }

The tag is the URL saved as a string.

Upvotes: 1

Views: 822

Answers (1)

Nico Zhu
Nico Zhu

Reputation: 32775

Is there any way to open a specific URL in a UWP app?

Sure, UWP has WebView control that use to render html page, you could give it uri source, then the WebView will render the website in the app. For more detail please refer Web view document.

<WebView x:Name="webView1" Source="http://www.contoso.com"/>

Update

You could also launch the default browser to load the uri like the following

private async void Button_Click(object sender, RoutedEventArgs e)
{
    string uriToLaunch = @"https://www.test.com";
    var uri = new Uri(uriToLaunch);

    // Set the option to show a warning
    var options = new Windows.System.LauncherOptions();
    options.TreatAsUntrusted = true;

    // Launch the URI with a warning prompt
    var success = await Windows.System.Launcher.LaunchUriAsync(uri, options);

    if (success)
    {
        // URI launched
    }
    else
    {
        // URI launch failed
    }

}

Upvotes: 1

Related Questions