Skip to content

Instantly share code, notes, and snippets.

@wcoder
Last active August 29, 2015 14:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wcoder/ef987866a535ab324294 to your computer and use it in GitHub Desktop.
Save wcoder/ef987866a535ab324294 to your computer and use it in GitHub Desktop.
using System;
using System.Threading.Tasks;
using Windows.UI.Xaml.Controls;
namespace POCWebViewUniversal
{
class Auth
{
private const string MainPage = "";
private const string LoginPage = "";
private const string LogoutPage = "";
private readonly WebView _webView = new WebView();
public delegate void AuthHandler(Auth sender);
public event AuthHandler OnLogin;
public event AuthHandler OnLogout;
public event AuthHandler OnNoAuth;
public string Html {
get { return GetHtml().Result; }
}
public string Cookie
{
get { return GetCookie().Result; }
}
public WebView WebView
{
get { return _webView; }
}
public Auth()
{
_webView.Source = new Uri(LoginPage);
_webView.NavigationCompleted += WebViewOnNavigationCompleted;
}
private void WebViewOnNavigationCompleted(WebView sender, WebViewNavigationCompletedEventArgs args)
{
var url = sender.Source.ToString();
if (url.Equals(MainPage))
{
OnLogin(this);
}
else if (url.Equals(LogoutPage))
{
OnLogout(this);
}
else if (url.Equals(LoginPage))
{
OnNoAuth(this);
}
}
public async Task Login(string username, string password)
{
var js = "";
js += string.Format("document.getElementById('username').value = '{0}';", username);
js += string.Format("document.getElementById('password').value = '{0}';", password);
js += "document.forms[0].getElementsByClassName('loginBtn')[1].click();";
await InvokeScript(js);
}
public async Task Logout()
{
var js = string.Format("location.href='{0}'", LogoutPage);
await InvokeScript(js);
}
public async Task<string> GetCookie()
{
var js = "document.cookie;";
return await InvokeScript(js);
}
public async Task<string> GetHtml()
{
var js = "document.documentElement.outerHTML;";
return await InvokeScript(js);
}
private async Task<string> InvokeScript(string js)
{
return await _webView.InvokeScriptAsync("eval", new[] { js });
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment