Core - Javascript Binding Configure Property Name

- Rename settings object to JavascriptBindingSettings
- Validate JavascriptBindingSettings.JsBindingGlobalObjectName in setter to provide immediate
  feedback
- Add FreezableBase which throws exception when frozen (we can reuse this for some other settings classes)
- Add some basic Unit Tests (More would be better)

Follow on from #3126
This commit is contained in:
amaitland
2020-05-19 21:55:16 +10:00
parent 66691105b4
commit ae41e10d71
19 changed files with 398 additions and 100 deletions
@@ -87,8 +87,17 @@ namespace CefSharp
}
}
_jsBindingPropertyName = extraInfo->GetString("JsBindingPropertyName");
_jsBindingPropertyNameCamelCase = extraInfo->GetString("JsBindingPropertyNameCamelCase");
if (extraInfo->HasKey("JsBindingPropertyName") || extraInfo->HasKey("JsBindingPropertyNameCamelCase"))
{
//TODO: Create constant for these and legacy binding strings above
_jsBindingPropertyName = extraInfo->GetString("JsBindingPropertyName");
_jsBindingPropertyNameCamelCase = extraInfo->GetString("JsBindingPropertyNameCamelCase");
}
else
{
_jsBindingPropertyName = "CefSharp";
_jsBindingPropertyNameCamelCase = "cefSharp";
}
}
void CefAppUnmanagedWrapper::OnBrowserDestroyed(CefRefPtr<CefBrowser> browser)
@@ -134,27 +143,33 @@ namespace CefSharp
auto isObjectCachedFunction = CefV8Value::CreateFunction(kIsObjectCached, new RegisterBoundObjectHandler(_javascriptObjects));
auto postMessageFunction = CefV8Value::CreateFunction(kPostMessage, new JavascriptPostMessageHandler(rootObject == nullptr ? nullptr : rootObject->CallbackRegistry));
if (!_jsBindingPropertyName.empty())
//By default We'll support both CefSharp and cefSharp, for those who prefer the JS style
auto createCefSharpObj = !_jsBindingPropertyName.empty();
auto createCefSharpObjCamelCase = !_jsBindingPropertyNameCamelCase.empty();
if (createCefSharpObj)
{
auto cefSharpObj = CefV8Value::CreateObject(NULL, NULL);
global->SetValue(_jsBindingPropertyName, cefSharpObj, CefV8Value::PropertyAttribute::V8_PROPERTY_ATTRIBUTE_READONLY);
cefSharpObj->SetValue(kBindObjectAsync, bindObjAsyncFunction, CefV8Value::PropertyAttribute::V8_PROPERTY_ATTRIBUTE_NONE);
cefSharpObj->SetValue(kDeleteBoundObject, unBindObjFunction, CefV8Value::PropertyAttribute::V8_PROPERTY_ATTRIBUTE_NONE);
cefSharpObj->SetValue(kRemoveObjectFromCache, removeObjectFromCacheFunction, CefV8Value::PropertyAttribute::V8_PROPERTY_ATTRIBUTE_NONE);
cefSharpObj->SetValue(kIsObjectCached, isObjectCachedFunction, CefV8Value::PropertyAttribute::V8_PROPERTY_ATTRIBUTE_NONE);
cefSharpObj->SetValue(kPostMessage, postMessageFunction, CefV8Value::PropertyAttribute::V8_PROPERTY_ATTRIBUTE_NONE);
global->SetValue(_jsBindingPropertyName, cefSharpObj, CefV8Value::PropertyAttribute::V8_PROPERTY_ATTRIBUTE_READONLY);
}
//We'll support both CefSharp and cefSharp, for those who prefer the JS style
auto cefSharpObjCamelCase = CefV8Value::CreateObject(NULL, NULL);
global->SetValue(_jsBindingPropertyNameCamelCase, cefSharpObjCamelCase, CefV8Value::PropertyAttribute::V8_PROPERTY_ATTRIBUTE_READONLY);
if (createCefSharpObjCamelCase)
{
auto cefSharpObjCamelCase = CefV8Value::CreateObject(NULL, NULL);
cefSharpObjCamelCase->SetValue(kBindObjectAsyncCamelCase, bindObjAsyncFunction, CefV8Value::PropertyAttribute::V8_PROPERTY_ATTRIBUTE_NONE);
cefSharpObjCamelCase->SetValue(kDeleteBoundObjectCamelCase, unBindObjFunction, CefV8Value::PropertyAttribute::V8_PROPERTY_ATTRIBUTE_NONE);
cefSharpObjCamelCase->SetValue(kRemoveObjectFromCacheCamelCase, removeObjectFromCacheFunction, CefV8Value::PropertyAttribute::V8_PROPERTY_ATTRIBUTE_NONE);
cefSharpObjCamelCase->SetValue(kIsObjectCachedCamelCase, isObjectCachedFunction, CefV8Value::PropertyAttribute::V8_PROPERTY_ATTRIBUTE_NONE);
cefSharpObjCamelCase->SetValue(kPostMessageCamelCase, postMessageFunction, CefV8Value::PropertyAttribute::V8_PROPERTY_ATTRIBUTE_NONE);
cefSharpObjCamelCase->SetValue(kBindObjectAsyncCamelCase, bindObjAsyncFunction, CefV8Value::PropertyAttribute::V8_PROPERTY_ATTRIBUTE_NONE);
cefSharpObjCamelCase->SetValue(kDeleteBoundObjectCamelCase, unBindObjFunction, CefV8Value::PropertyAttribute::V8_PROPERTY_ATTRIBUTE_NONE);
cefSharpObjCamelCase->SetValue(kRemoveObjectFromCacheCamelCase, removeObjectFromCacheFunction, CefV8Value::PropertyAttribute::V8_PROPERTY_ATTRIBUTE_NONE);
cefSharpObjCamelCase->SetValue(kIsObjectCachedCamelCase, isObjectCachedFunction, CefV8Value::PropertyAttribute::V8_PROPERTY_ATTRIBUTE_NONE);
cefSharpObjCamelCase->SetValue(kPostMessageCamelCase, postMessageFunction, CefV8Value::PropertyAttribute::V8_PROPERTY_ATTRIBUTE_NONE);
global->SetValue(_jsBindingPropertyNameCamelCase, cefSharpObjCamelCase, CefV8Value::PropertyAttribute::V8_PROPERTY_ATTRIBUTE_READONLY);
}
//Send a message to the browser processing signaling that OnContextCreated has been called
//only param is the FrameId. Previous sent only for main frame, now sent for all frames
@@ -28,7 +28,7 @@ namespace CefSharp
bool _focusedNodeChangedEnabled;
bool _legacyBindingEnabled;
// The property names used to call binded objects
// The property names used to call bound objects
CefString _jsBindingPropertyName;
CefString _jsBindingPropertyNameCamelCase;
+10 -16
View File
@@ -66,24 +66,18 @@ void ManagedCefBrowserAdapter::CreateBrowser(IWindowInfo^ windowInfo, BrowserSet
extraInfo->SetBool("LegacyBindingEnabled", legacyBindingEnabled);
// Retrieve the configurable binding property names, throw exception if empty or illegal characters
auto jsBindingPropertyName = _javaScriptObjectRepository->Settings->WindowPropertyName;
if (!StringCheck::EnsureLettersAndNumbers(jsBindingPropertyName))
if (!String::IsNullOrEmpty(objectRepository->Settings->JavascriptBindingApiGlobalObjectName))
{
throw gcnew InvalidOperationException("CefBrowserHost::CreateBrowser invalid or illegal characters used for binding property names. Alphanumeric and underscores characters only.");
}
auto globalObjName = objectRepository->Settings->JavascriptBindingApiGlobalObjectName;
if (_javaScriptObjectRepository->Settings->IsWindowPropertyNameCamelCase())
{
extraInfo->SetString("JsBindingPropertyNameCamelCase", StringUtils::ToNative(jsBindingPropertyName));
}
else
{
extraInfo->SetString("JsBindingPropertyName", StringUtils::ToNative(jsBindingPropertyName));
// Convert to camelCase
auto camelCasePropertyName = _javaScriptObjectRepository->ConvertStringToCamelCase(jsBindingPropertyName);
extraInfo->SetString("JsBindingPropertyNameCamelCase", StringUtils::ToNative(camelCasePropertyName));
if (StringCheck::IsFirstCharacterLowercase(globalObjName))
{
extraInfo->SetString("JsBindingPropertyNameCamelCase", StringUtils::ToNative(globalObjName));
}
else
{
extraInfo->SetString("JsBindingPropertyName", StringUtils::ToNative(globalObjName));
}
}
if (!CefBrowserHost::CreateBrowser(*cefWindowInfoWrapper->GetWindowInfo(), _clientAdapter.get(), addressNative,
+4 -2
View File
@@ -16,7 +16,8 @@ namespace CefSharp.Example
{
//TODO: Revert after https://bitbucket.org/chromiumembedded/cef/issues/2685/networkservice-custom-scheme-unable-to
//has been fixed.
public const string BaseUrl = "https://cefsharp.example";
public const string ExampleDomain = "cefsharp.example";
public const string BaseUrl = "https://" + ExampleDomain;
public const string DefaultUrl = BaseUrl + "/home.html";
public const string BindingTestUrl = BaseUrl + "/BindingTest.html";
public const string BindingTestSingleUrl = BaseUrl + "/BindingTestSingle.html";
@@ -32,6 +33,7 @@ namespace CefSharp.Example
public const string DragDropCursorsTestUrl = BaseUrl + "/DragDropCursorsTest.html";
public const string CssAnimationTestUrl = BaseUrl + "/CssAnimationTest.html";
public const string CdmSupportTestUrl = BaseUrl + "/CdmSupportTest.html";
public const string BindingApiCustomObjectNameTestUrl = BaseUrl + "/BindingApiCustomObjectNameTest.html";
public const string TestResourceUrl = "http://test/resource/load";
public const string RenderProcessCrashedUrl = "http://processcrashed";
public const string TestUnicodeResourceUrl = "http://test/resource/loadUnicode";
@@ -171,7 +173,7 @@ namespace CefSharp.Example
{
SchemeName = "https",
SchemeHandlerFactory = new CefSharpSchemeHandlerFactory(),
DomainName = "cefsharp.example"
DomainName = ExampleDomain
});
settings.RegisterScheme(new CefCustomScheme
+1
View File
@@ -150,6 +150,7 @@
<None Include="Resources\assets\js\shBrushJScript.js" />
<Content Include="Resources\assets\js\shCore.js" />
<Content Include="Resources\BindingTestsAsyncTask.html" />
<Content Include="Resources\BindingApiCustomObjectNameTest.html" />
<Content Include="Resources\BindingTestSingle.html" />
<Content Include="Resources\DragDropCursorsTest.html" />
<Content Include="Resources\JavascriptCallbackTest.html" />
@@ -55,7 +55,8 @@ namespace CefSharp.Example
{ "/UnicodeExampleGreaterThan32kb.html", Resources.UnicodeExampleGreaterThan32kb },
{ "/UnocodeExampleEqualTo32kb.html", Resources.UnocodeExampleEqualTo32kb },
{ "/JavascriptCallbackTest.html", Resources.JavascriptCallbackTest },
{ "/BindingTestsAsyncTask.html", Resources.BindingTestsAsyncTask }
{ "/BindingTestsAsyncTask.html", Resources.BindingTestsAsyncTask },
{ "/BindingApiCustomObjectNameTest.html", Resources.BindingApiCustomObjectNameTest }
};
}
+58 -30
View File
@@ -282,23 +282,49 @@ namespace CefSharp.Example.Properties {
}
}
/// <summary>
/// Looks up a localized string similar to &lt;!DOCTYPE html&gt;
///&lt;html&gt;
///&lt;head&gt;
/// &lt;meta charset=&quot;utf-8&quot;&gt;
/// &lt;title&gt;QUnit Javascript Binding API Object Name&lt;/title&gt;
/// &lt;link rel=&quot;stylesheet&quot; href=&quot;https://code.jquery.com/qunit/qunit-2.10.0.css&quot;&gt;
/// &lt;script&gt;
/// if (!window.bindingApiObject)
/// {
/// window.bindingApiObject = cefSharp;
/// }
/// &lt;/script&gt;
///&lt;/head&gt;
///&lt;body&gt;
/// &lt;div id=&quot;qunit&quot;&gt;&lt;/div&gt;
/// &lt;div id=&quot;qunit-fixture&quot;&gt;&lt;/div&gt;
/// &lt;script src=&quot;https://code.jquery.com/qunit/qunit-2.10.0.js&quot;&gt;&lt;/script&gt;
/// &lt;script&gt; [rest of string was truncated]&quot;;.
/// </summary>
public static string BindingApiCustomObjectNameTest {
get {
return ResourceManager.GetString("BindingApiCustomObjectNameTest", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to &lt;!DOCTYPE HTML PUBLIC &quot;-//W3C//DTD HTML 4.0 Transitional//EN&quot;&gt;
///&lt;html&gt;
/// &lt;head&gt;
/// &lt;title&gt;Binding Test&lt;/title&gt;
/// &lt;link rel=&quot;stylesheet&quot; href=&quot;https://code.jquery.com/qunit/qunit-2.4.1.css&quot;&gt;
/// &lt;/head&gt;
/// &lt;body&gt;
/// &lt;div id=&quot;qunit&quot;&gt;&lt;/div&gt;
/// &lt;div id=&quot;qunit-fixture&quot;&gt;&lt;/div&gt;
/// &lt;script src=&quot;https://code.jquery.com/qunit/qunit-2.4.1.js&quot;&gt;&lt;/script&gt;
///&lt;head&gt;
/// &lt;title&gt;Binding Test&lt;/title&gt;
/// &lt;link rel=&quot;stylesheet&quot; href=&quot;https://code.jquery.com/qunit/qunit-2.4.1.css&quot;&gt;
///&lt;/head&gt;
///&lt;body&gt;
/// &lt;div id=&quot;qunit&quot;&gt;&lt;/div&gt;
/// &lt;div id=&quot;qunit-fixture&quot;&gt;&lt;/div&gt;
/// &lt;script src=&quot;https://code.jquery.com/qunit/qunit-2.4.1.js&quot;&gt;&lt;/script&gt;
///
/// &lt;!--&lt;script type=&quot;text/javascript&quot;&gt;
/// (async function() {
/// // &lt;embed user provided code here&gt;
/// &lt;!--&lt;script type=&quot;text/javascript&quot;&gt;
/// (async function() {
/// // &lt;embed user provided code here&gt;
///
/// [rest of string was truncated]&quot;;.
/// await CefSharp.BindObjectAsync(&quot;boundAsy [rest of string was truncated]&quot;;.
/// </summary>
public static string BindingTest {
get {
@@ -339,16 +365,16 @@ namespace CefSharp.Example.Properties {
/// &lt;link rel=&quot;stylesheet&quot; href=&quot;https://code.jquery.com/qunit/qunit-2.4.1.css&quot;&gt;
///&lt;/head&gt;
///&lt;body&gt;
/// &lt;div&gt;
/// These tests require CefSharpSettings.ConcurrentTaskExecution = true;
/// Which by default is set to false
/// &lt;/div&gt;
///
/// &lt;div id=&quot;qunit&quot;&gt;&lt;/div&gt;
/// &lt;div id=&quot;qunit-fixture&quot;&gt;&lt;/div&gt;
/// &lt;script src=&quot;https://code.jquery.com/qunit/qunit-2.4.1.js&quot;&gt;&lt;/script&gt;
///
/// &lt;script typ [rest of string was truncated]&quot;;.
/// &lt;script type=&quot;text/javascript&quot;&gt;
/// (async () =&gt;
/// {
/// await CefSharp.BindObjectAsync(&quot;boundAsync&quot;);
///
/// QUnit.test(&quot;Async [rest of string was truncated]&quot;;.
/// </summary>
public static string BindingTestSingle {
get {
@@ -659,17 +685,17 @@ namespace CefSharp.Example.Properties {
/// <summary>
/// Looks up a localized string similar to &lt;!DOCTYPE HTML PUBLIC &quot;-//W3C//DTD HTML 4.0 Transitional//EN&quot;&gt;
///&lt;html&gt;
/// &lt;head&gt;
/// &lt;title&gt;Popup Test&lt;/title&gt;
/// &lt;/head&gt;
/// &lt;body&gt;
/// &lt;a href=&quot;https://github.com/CefSharp/CefSharp&quot; target=&quot;_blank&quot;&gt;target=_blank&lt;/a&gt;
/// &lt;br /&gt;
/// &lt;a href=&quot;#&quot; onclick=&quot;window.open(&apos;https://github.com/CefSharp/CefSharp&apos;)&quot;&gt;window.open()&lt;/a&gt;
/// &lt;br /&gt;
/// &lt;a href=&quot;#&quot; onclick=&quot;window.open(&apos;custom://cefsharp/BindingTest.html&apos;)&quot;&gt;BindingTest.html&lt;/a&gt;
/// &lt;br /&gt;
/// &lt;a href=&quot;#&quot; onclick [rest of string was truncated]&quot;;.
///&lt;head&gt;
/// &lt;title&gt;Popup Test&lt;/title&gt;
///&lt;/head&gt;
///&lt;body&gt;
/// &lt;a href=&quot;https://github.com/CefSharp/CefSharp&quot; target=&quot;_blank&quot;&gt;target=_blank&lt;/a&gt;
/// &lt;br /&gt;
/// &lt;a href=&quot;#&quot; onclick=&quot;window.open(&apos;https://github.com/CefSharp/CefSharp&apos;)&quot;&gt;window.open()&lt;/a&gt;
/// &lt;br /&gt;
/// &lt;a href=&quot;#&quot; onclick=&quot;window.open(&apos;custom://cefsharp/BindingTest.html&apos;)&quot;&gt;BindingTest.html&lt;/a&gt;
/// &lt;br /&gt;
/// &lt;a href=&quot;#&quot; onclick=&quot;window.open(&apos;custom://cefsharp/MultiBindin [rest of string was truncated]&quot;;.
/// </summary>
public static string PopupTest {
get {
@@ -692,9 +718,11 @@ namespace CefSharp.Example.Properties {
/// &lt;script src=&quot;https://code.jquery.com/qunit/qunit-2.4.1.js&quot;&gt;&lt;/script&gt;
///
/// &lt;script type=&quot;text/javascript&quot;&gt;
/// let PostMessageIntTestCallback;
///
/// (async () =&gt;
/// {
/// QUnit.test(&quot;PostMessage Test:&quot;, function [rest of string was truncated]&quot;;.
/// [rest of string was truncated]&quot;;.
/// </summary>
public static string PostMessageTest {
get {
@@ -223,4 +223,7 @@
<data name="PostMessageTest" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\Resources\PostMessageTest.html;System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089;Windows-1252</value>
</data>
<data name="BindingApiCustomObjectNameTest" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\Resources\BindingApiCustomObjectNameTest.html;System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089;Windows-1252</value>
</data>
</root>
@@ -0,0 +1,25 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>QUnit Javascript Binding API Object Name</title>
<link rel="stylesheet" href="https://code.jquery.com/qunit/qunit-2.10.0.css">
<script>
if (!window.bindingApiObject)
{
window.bindingApiObject = cefSharp;
}
</script>
</head>
<body>
<div id="qunit"></div>
<div id="qunit-fixture"></div>
<script src="https://code.jquery.com/qunit/qunit-2.10.0.js"></script>
<script>
QUnit.test("Test if can execute a method on our object", function (assert)
{
assert.notOk(bindingApiObject.isObjectCached("fakeExample"), "We expect false");
});
</script>
</body>
</html>
@@ -649,6 +649,11 @@
});
});
});
QUnit.done(function (details)
{
CefSharp.PostMessage({ "Type" : "QUnitExecutionComplete", "Details" : details });
});
</script>
</body>
+1
View File
@@ -130,6 +130,7 @@
<Compile Include="Framework\ConcurrentMethodRunnerQueueFacts.cs" />
<Compile Include="Framework\MimeTypeMappingFacts.cs" />
<Compile Include="Framework\PathCheckFacts.cs" />
<Compile Include="JavascriptBinding\IntegrationTestFacts.cs" />
<Compile Include="OffScreen\OffScreenBrowserBasicFacts.cs" />
<Compile Include="CefSharpXunitTestFramework.cs" />
<Compile Include="CefSharpFixture.cs" />
+8
View File
@@ -5,6 +5,7 @@
using System;
using System.IO;
using System.Threading.Tasks;
using CefSharp.Example;
using CefSharp.OffScreen;
using Nito.AsyncEx;
using Xunit;
@@ -35,6 +36,13 @@ namespace CefSharp.Test
CefSharpSettings.ShutdownOnExit = false;
var settings = new CefSettings();
settings.RegisterScheme(new CefCustomScheme
{
SchemeName = "https",
SchemeHandlerFactory = new CefSharpSchemeHandlerFactory(),
DomainName = CefExample.ExampleDomain
});
//The location where cache data will be stored on disk. If empty an in-memory cache will be used for some features and a temporary disk cache for others.
//HTML5 databases such as localStorage will only persist across sessions if a cache path is specified.
settings.CachePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "CefSharp\\Tests\\Cache");
@@ -0,0 +1,95 @@
// Copyright © 2020 The CefSharp Authors. All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.
using System.Threading.Tasks;
using CefSharp.Example;
using CefSharp.Example.JavascriptBinding;
using CefSharp.OffScreen;
using Xunit;
using Xunit.Abstractions;
namespace CefSharp.Test.JavascriptBinding
{
/// <summary>
/// This is more a set of integration tests than it is unit tests, for now we need to
/// run our QUnit tests in an automated fashion and some other testing.
/// </summary>
//TODO: Improve Test Naming, we need a naming scheme that fits these cases that's consistent
//(Ideally we implement consistent naming accross all test classes, though I'm open to a different
//naming convention as these are more integration tests than unit tests).
//NOTE: All Test classes must be part of this collection as it manages the Cef Initialize/Shutdown lifecycle
[Collection(CefSharpFixtureCollection.Key)]
public class IntegrationTestFacts
{
private readonly ITestOutputHelper output;
private readonly CefSharpFixture fixture;
public IntegrationTestFacts(ITestOutputHelper output, CefSharpFixture fixture)
{
this.fixture = fixture;
this.output = output;
}
[Fact]
public async Task LoadJavaScriptBindingQunitTestsSuccessfulCompletion()
{
using (var browser = new ChromiumWebBrowser(CefExample.BindingTestUrl, automaticallyCreateBrowser: false))
{
//TODO: Extract this into some sort of helper setup method
var bindingOptions = BindingOptions.DefaultBinder;
var repo = browser.JavascriptObjectRepository;
repo.Register("bound", new BoundObject(), isAsync: false, options: bindingOptions);
repo.Register("boundAsync", new AsyncBoundObject(), isAsync: true, options: bindingOptions);
repo.Register("boundAsync2", new AsyncBoundObject(), isAsync: true, options: bindingOptions);
browser.CreateBrowser();
var success = await browser.WaitForQUnitTestExeuctionToComplete();
Assert.True(success);
output.WriteLine("QUnit Tests result: {0}", success);
}
}
[Fact]
public async Task IsObjectCachedWithInvalidObjectNameReturnsFalse()
{
using (var browser = new ChromiumWebBrowser(CefExample.BindingApiCustomObjectNameTestUrl))
{
await browser.LoadPageAsync();
//We'll execute twice using the different cased (camelcase naming and standard)
var response = await browser.EvaluateScriptAsync("CefSharp.IsObjectCached('doesntexist')");
Assert.True(response.Success);
Assert.False((bool)response.Result);
response = await browser.EvaluateScriptAsync("cefSharp.isObjectCached('doesntexist')");
Assert.True(response.Success);
Assert.False((bool)response.Result);
}
}
[Fact]
public async Task JsBindingGlobalObjectNameCustomValueExecuteIsObjectCachedSuccess()
{
using (var browser = new ChromiumWebBrowser(CefExample.BindingApiCustomObjectNameTestUrl, automaticallyCreateBrowser: false))
{
var settings = browser.JavascriptObjectRepository.Settings;
settings.JavascriptBindingApiGlobalObjectName = "customApi";
//To modify the settings we need to defer browser creation slightly
browser.CreateBrowser();
await browser.LoadPageAsync();
var result = await browser.EvaluateScriptAsync("customApi.isObjectCached('doesntexist') === false");
Assert.True(result.Success);
}
}
}
}
@@ -0,0 +1,63 @@
// Copyright © 2020 The CefSharp Authors. All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.
using System.Threading.Tasks;
using CefSharp.Example;
using CefSharp.OffScreen;
using Xunit;
using Xunit.Abstractions;
namespace CefSharp.Test.JavascriptBinding
{
/// <summary>
/// This is more of a set of integration tests than it is unit tests, for now we need to
/// run our QUnit tests in an automated fashion and some other testing.
/// Long term we should split this out into full integration tests.
/// </summary>
//NOTE: All Test classes must be part of this collection as it manages the Cef Initialize/Shutdown lifecycle
[Collection(CefSharpFixtureCollection.Key)]
public class JavascriptBindingFacts
{
private readonly ITestOutputHelper output;
private readonly CefSharpFixture fixture;
public JavascriptBindingFacts(ITestOutputHelper output, CefSharpFixture fixture)
{
this.fixture = fixture;
this.output = output;
}
[Fact]
public async Task RunJavascriptBindingQunitTests()
{
using (var browser = new ChromiumWebBrowser(CefExample.BindingTestUrl))
{
var success = await browser.WaitForQUnitTestExeuctionToComplete();
Assert.True(success);
output.WriteLine("QUnit Tests result: {0}", success);
}
}
[Fact]
public async Task CanModifyJavascriptBindingWindowObjectName()
{
using (var browser = new ChromiumWebBrowser(CefExample.DefaultUrl, automaticallyCreateBrowser: false))
{
var settings = browser.JavascriptObjectRepository.Settings;
settings.JsBindingGlobalObjectName = "customApi";
//To modify the settings we need to defer browser creation slightly
browser.CreateBrowser();
await browser.LoadPageAsync();
var result = await browser.EvaluateScriptAsync("customApi.IsObjectCached('doesntexist') === false");
Assert.True(result.Success);
}
}
}
}
+32
View File
@@ -36,5 +36,37 @@ namespace CefSharp.Test
}
return tcs.Task;
}
public static Task<bool> WaitForQUnitTestExeuctionToComplete(this IWebBrowser browser)
{
//If using .Net 4.6 then use TaskCreationOptions.RunContinuationsAsynchronously
//and switch to tcs.TrySetResult below - no need for the custom extension method
var tcs = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
EventHandler<JavascriptMessageReceivedEventArgs> handler = null;
handler = (sender, args) =>
{
browser.JavascriptMessageReceived -= handler;
dynamic msg = args.Message;
//Wait for while page to finish loading not just the first frame
if (msg.Type == "QUnitExecutionComplete")
{
var details = msg.Details;
var total = (int)details.total;
var passed = (int)details.passed;
tcs.TrySetResult(total == passed);
}
else
{
tcs.TrySetException(new Exception("WaitForQUnitTestExeuctionToComplete - Incorrect Message Type"));
}
};
browser.JavascriptMessageReceived += handler;
return tcs.Task;
}
}
}
@@ -59,17 +59,17 @@ namespace CefSharp.Wpf.Example.Views
}
else
{
if (e.ObjectName == "boundAsync2")
if (e.ObjectName == "bound")
{
repo.Register("boundAsync2", new AsyncBoundObject(), isAsync: true, options: bindingOptions);
}
else if (e.ObjectName == "bound")
{
browser.JavascriptObjectRepository.Register("bound", new BoundObject(), isAsync: false, options: BindingOptions.DefaultBinder);
repo.Register("bound", new BoundObject(), isAsync: false, options: BindingOptions.DefaultBinder);
}
else if (e.ObjectName == "boundAsync")
{
browser.JavascriptObjectRepository.Register("boundAsync", new AsyncBoundObject(), isAsync: true, options: bindingOptions);
repo.Register("boundAsync", new AsyncBoundObject(), isAsync: true, options: bindingOptions);
}
else if (e.ObjectName == "boundAsync2")
{
repo.Register("boundAsync2", new AsyncBoundObject(), isAsync: true, options: bindingOptions);
}
}
};
@@ -168,11 +168,15 @@ namespace CefSharp.Wpf.Example.Views
//dynamic msg = e.Message;
//Alternatively you can use the built in Model Binder to convert to a custom model
var msg = e.ConvertMessageTo<PostMessageExample>();
var callback = msg.Callback;
var type = msg.Type;
var property = msg.Data.Property;
callback.ExecuteAsync(type);
if (msg.Type == "Update")
{
var callback = msg.Callback;
var type = msg.Type;
var property = msg.Data.Property;
callback.ExecuteAsync(type);
}
}
else if (e.Message is int)
{
@@ -1,21 +0,0 @@
// Copyright © 2020 The CefSharp Authors. All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.
namespace CefSharp.Internals
{
public class JavascriptObjectRepositorySettings
{
public string WindowPropertyName { get; set; }
public JavascriptObjectRepositorySettings()
{
WindowPropertyName = "CefSharp";
}
public bool IsWindowPropertyNameCamelCase()
{
return StringCheck.IsFirstCharacterLowercase(WindowPropertyName);
}
}
}
+13 -5
View File
@@ -6,23 +6,31 @@ using System.Text.RegularExpressions;
namespace CefSharp.Internals
{
/// <summary>
/// String validation
/// </summary>
public static class StringCheck
{
/// <summary>
/// Regex check to ensure string contains only letters, numbers and underscores.
/// </summary>
/// <param name="stringToCheck"></param>
/// <returns></returns>
public static bool EnsureLettersAndNumbers(string stringToCheck)
/// <returns>false if string is invalid</returns>
public static bool IsLettersAndNumbers(string stringToCheck)
{
if (!string.IsNullOrWhiteSpace(stringToCheck))
if (string.IsNullOrWhiteSpace(stringToCheck))
{
return Regex.IsMatch(stringToCheck, @"^\w+$");
return false;
}
return false;
return Regex.IsMatch(stringToCheck, @"^\w+$");
}
/// <summary>
/// Return true if the first chracter of the specified string is lowercase
/// </summary>
/// <param name="str">string</param>
/// <returns>returns false if empty or null, otherwise true if first character is lowercase</returns>
public static bool IsFirstCharacterLowercase(string str)
{
if (!string.IsNullOrEmpty(str))
+34
View File
@@ -10,6 +10,37 @@ namespace CefSharp.Internals
public class JavascriptBindingSettings : FreezableBase
{
private bool legacyBindingEnabled;
private string jsBindingGlobalObjectName;
/// <summary>
/// The Javascript methods that CefSharp provides in relation to JavaScript Binding are
/// created using a Global (window) Object. Settings this property allows you to customise
/// the name of this object. If not specified then both cefSharp and CefSharp objects will
/// be created e.g. cefSharp.bindObjectAsync, CefSharp.BindObjectAsync.
/// If specified then your custom name will be used, if the name starts with a lowercase letter
/// then all the functions will be lowercase, e.g. myObjName.bindObjectAsync otherwise
/// the functions will start with a uppercase letter e.g. MyObjName.BindObjectAsync
/// </summary>
/// <remarks>
/// This object is also accessible through the window property. e.g. window.cefSharp.bindObjectAsync
/// </remarks>
public string JavascriptBindingApiGlobalObjectName
{
get { return jsBindingGlobalObjectName; }
set
{
ThrowIfFrozen();
if (!StringCheck.IsLettersAndNumbers(value))
{
//TODO: See if there's a better suited Exception class for this.
throw new System.Exception("invalid or illegal characters used for binding property names. Alphanumeric and underscores characters only.");
}
jsBindingGlobalObjectName = value;
}
}
/// <summary>
/// Objects registered using <see cref="IJavascriptObjectRepository.Register(string, object, bool, BindingOptions)"/>
/// will be automatically bound when a V8Context is created. (Soon as the Javascript
@@ -27,6 +58,9 @@ namespace CefSharp.Internals
}
}
/// <summary>
/// Default Constructor
/// </summary>
public JavascriptBindingSettings()
{
//Default to CefSharpSettings.LegacyJavascriptBindingEnabled