1
0
mirror of https://github.com/chylex/TweetDuck.git synced 2025-04-24 06:15:48 +02:00

Move IScriptExecutor.RunFunction into an extension method

This commit is contained in:
chylex 2022-01-18 11:36:15 +01:00
parent 655d334714
commit af5d785ff2
Signed by: chylex
GPG Key ID: 4DE42C8F19A80548
2 changed files with 54 additions and 6 deletions
Browser/Adapters
lib/TweetLib.Browser/Interfaces

View File

@ -96,10 +96,6 @@ public void AttachBridgeObject(string name, object bridge) {
browser.JavascriptObjectRepository.Register(name, bridge, isAsync: true, BindingOptions.DefaultBinder);
}
public void RunFunction(string name, params object[] args) {
browser.BrowserCore.ExecuteScriptAsync(name, args);
}
public void RunScript(string identifier, string script) {
using IFrame frame = browser.GetMainFrame();
frame.ExecuteJavaScriptAsync(script, identifier, 1);

View File

@ -1,6 +1,58 @@
namespace TweetLib.Browser.Interfaces {
using System;
using System.Globalization;
using System.Text;
namespace TweetLib.Browser.Interfaces {
public interface IScriptExecutor {
void RunFunction(string name, params object[] args);
void RunScript(string identifier, string script);
}
public static class ScriptExecutorExtensions {
public static void RunFunction(this IScriptExecutor executor, string name, params object?[] args) {
executor.RunScript("about:blank", GenerateJavaScriptFunctionCall(name, args));
}
private static string GenerateJavaScriptFunctionCall(string name, object?[] args) {
var builder = new StringBuilder();
builder.Append(name);
builder.Append('(');
for (var index = 0; index < args.Length; index++) {
var obj = args[index];
switch (obj) {
case null:
builder.Append("null");
break;
case bool b:
builder.Append(b.ToString().ToLowerInvariant());
break;
case sbyte or byte or short or ushort or int or uint or long or ulong or float or double or decimal:
builder.Append(Convert.ToString(obj, CultureInfo.InvariantCulture));
break;
default:
var str = obj.ToString() ?? string.Empty;
var escaped = str.Replace("\\", "\\\\")
.Replace("'", "\\'")
.Replace("\t", "\\t")
.Replace("\r", "\\r")
.Replace("\n", "\\n");
builder.Append('\'');
builder.Append(escaped);
builder.Append('\'');
break;
}
if (index < args.Length - 1) {
builder.Append(',');
}
}
return builder.Append(");").ToString();
}
}
}