Skip to content

Instantly share code, notes, and snippets.

@prabirshrestha
Created June 2, 2012 18:17
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save prabirshrestha/2859454 to your computer and use it in GitHub Desktop.
Save prabirshrestha/2859454 to your computer and use it in GitHub Desktop.
WP7 web browser script extensions
using System;
using Microsoft.Phone.Controls;
public static class WebBrowserScriptExtensions
{
public static object ExecuteCode(this WebBrowser browser, string code)
{
return browser.InvokeScript("eval", "(function(){\r\n" + code + "\r\n})();");
}
public static object SetVariable(this WebBrowser browser, string name, string code, bool overrideScript = false)
{
if (overrideScript)
{
return browser.InvokeScript("eval",
"this." + name + " = " + code + ";");
}
else
{
return browser.InvokeScript("eval",
"if(!this." + name + ") {\r\n" + "this." + name + " = " + code + "; \r\n}");
}
}
public static object NotifyOnScriptError(this WebBrowser browser, string code = "", bool overrideScript = false)
{
if (string.IsNullOrEmpty(code))
{
code = "window.external.notify(JSON.stringify({message: message, file: file, line: line}));";
}
return browser.SetVariable("onerror", "function(message, file, line) {\r\n " + code + "\r\n}", overrideScript);
}
public static string GetHtml(this WebBrowser browser)
{
return (string)browser.ExecuteCode("return document.documentElement.outerHTML");
}
public class JavascriptExecption : Exception
{
public JavascriptExecption(string message, string file, long line)
: base(message)
{
File = file;
Line = line;
}
public JavascriptExecption(string message, string file, string line)
: this(message, file, long.Parse(line))
{
}
public string File { get; private set; }
public long Line { get; private set; }
}
}
var x = webBrowser1.SetVariable("msg", @"function() { return 'hi'; }");
var y = webBrowser1.InvokeScript("msg"); // y === 'hi'
webBrowser1.NotifyOnScriptError();
webBrowser1.ExecuteCode("throw new Error('heello')");
private void webBrowser1_ScriptNotify(object sender, NotifyEventArgs e)
{
Debug.WriteLine(e.Value);
}
var z = webBrowser1.ExecuteCode("window.external.notify('hi');");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment