Created
June 2, 2012 18:17
-
-
Save prabirshrestha/2859454 to your computer and use it in GitHub Desktop.
WP7 web browser script extensions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; } | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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