Skip to content

Enhancement - Add EvaluateScriptAsPromiseAsync #3251

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Oct 6, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 25 additions & 8 deletions CefSharp.BrowserSubprocess.Core/CefAppUnmanagedWrapper.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
#include "BindObjectAsyncHandler.h"
#include "JavascriptPostMessageHandler.h"
#include "JavascriptRootObjectWrapper.h"
#include "JavascriptPromiseHandler.h"
#include "Async\JavascriptAsyncMethodCallback.h"
#include "Serialization\V8Serialization.h"
#include "Serialization\JsObjectsSerialization.h"
Expand Down Expand Up @@ -146,6 +147,7 @@ namespace CefSharp
auto removeObjectFromCacheFunction = CefV8Value::CreateFunction(kRemoveObjectFromCache, new RegisterBoundObjectHandler(_javascriptObjects));
auto isObjectCachedFunction = CefV8Value::CreateFunction(kIsObjectCached, new RegisterBoundObjectHandler(_javascriptObjects));
auto postMessageFunction = CefV8Value::CreateFunction(kPostMessage, new JavascriptPostMessageHandler(rootObject == nullptr ? nullptr : rootObject->CallbackRegistry));
auto promiseHandlerFunction = CefV8Value::CreateFunction(kSendEvalScriptResponse, new JavascriptPromiseHandler());

//By default We'll support both CefSharp and cefSharp, for those who prefer the JS style
auto createCefSharpObj = !_jsBindingPropertyName.empty();
Expand All @@ -159,6 +161,7 @@ namespace CefSharp
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);
cefSharpObj->SetValue(kSendEvalScriptResponse, promiseHandlerFunction, CefV8Value::PropertyAttribute::V8_PROPERTY_ATTRIBUTE_NONE);
cefSharpObj->SetValue(kRenderProcessId, CefV8Value::CreateInt(processId), CefV8Value::PropertyAttribute::V8_PROPERTY_ATTRIBUTE_NONE);

global->SetValue(_jsBindingPropertyName, cefSharpObj, CefV8Value::PropertyAttribute::V8_PROPERTY_ATTRIBUTE_READONLY);
Expand All @@ -172,6 +175,7 @@ namespace CefSharp
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(kSendEvalScriptResponseCamelCase, promiseHandlerFunction, CefV8Value::PropertyAttribute::V8_PROPERTY_ATTRIBUTE_NONE);
cefSharpObjCamelCase->SetValue(kRenderProcessIdCamelCase, CefV8Value::CreateInt(processId), CefV8Value::PropertyAttribute::V8_PROPERTY_ATTRIBUTE_NONE);

global->SetValue(_jsBindingPropertyNameCamelCase, cefSharpObjCamelCase, CefV8Value::PropertyAttribute::V8_PROPERTY_ATTRIBUTE_READONLY);
Expand Down Expand Up @@ -376,6 +380,7 @@ namespace CefSharp
//these messages are roughly handled the same way
if (name == kEvaluateJavascriptRequest || name == kJavascriptCallbackRequest)
{
bool sendResponse = true;
bool success = false;
CefRefPtr<CefV8Value> result;
CefString errorMessage;
Expand Down Expand Up @@ -433,8 +438,17 @@ namespace CefSharp
//we need to do this here to be able to store the v8context
if (success)
{
auto responseArgList = response->GetArgumentList();
SerializeV8Object(result, responseArgList, 2, callbackRegistry);
//If the response is a string of CefSharpDefEvalScriptRes then
//we don't send the response, we'll let that happen when the promise has completed.
if (result->IsString() && result->GetStringValue() == "CefSharpDefEvalScriptRes")
{
sendResponse = false;
}
else
{
auto responseArgList = response->GetArgumentList();
SerializeV8Object(result, responseArgList, 2, callbackRegistry);
}
}
else
{
Expand Down Expand Up @@ -521,14 +535,17 @@ namespace CefSharp
}
}

auto responseArgList = response->GetArgumentList();
responseArgList->SetBool(0, success);
SetInt64(responseArgList, 1, callbackId);
if (!success)
if (sendResponse)
{
responseArgList->SetString(2, errorMessage);
auto responseArgList = response->GetArgumentList();
responseArgList->SetBool(0, success);
SetInt64(responseArgList, 1, callbackId);
if (!success)
{
responseArgList->SetString(2, errorMessage);
}
frame->SendProcessMessage(sourceProcessId, response);
}
frame->SendProcessMessage(sourceProcessId, response);

handled = true;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -175,6 +175,7 @@
<ClInclude Include="BindObjectAsyncHandler.h" />
<ClCompile Include="BrowserSubprocessExecutable.h" />
<ClInclude Include="Cef.h" />
<ClInclude Include="JavascriptPromiseHandler.h" />
<ClInclude Include="SubProcessApp.h" />
<ClInclude Include="Async\JavascriptAsyncMethodCallback.h" />
<ClInclude Include="Async\JavascriptAsyncMethodHandler.h" />
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,9 @@
<ClInclude Include="Cef.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="JavascriptPromiseHandler.h">
<Filter>Header Files</Filter>
</ClInclude>
</ItemGroup>
<ItemGroup>
<ClCompile Include="AssemblyInfo.cpp">
Expand Down
85 changes: 85 additions & 0 deletions CefSharp.BrowserSubprocess.Core/JavascriptPromiseHandler.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
// 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.

#pragma once

#include "include/cef_v8.h"
#include "..\CefSharp.Core\Internals\Messaging\Messages.h"
#include "..\CefSharp.Core\Internals\Serialization\Primitives.h"
#include "Serialization\V8Serialization.h"

using namespace System;
using namespace CefSharp::Internals::Messaging;
using namespace CefSharp::Internals::Serialization;

namespace CefSharp
{
const CefString kSendEvalScriptResponse = CefString("SendEvalScriptResponse");
const CefString kSendEvalScriptResponseCamelCase = CefString("sendEvalScriptResponse");

private class JavascriptPromiseHandler : public CefV8Handler
{
public:

virtual bool Execute(const CefString& name,
CefRefPtr<CefV8Value> object,
const CefV8ValueList& arguments,
CefRefPtr<CefV8Value>& retval,
CefString& exception)
{
if (arguments.size() < 2)
{
//TODO: Improve error message
exception = "Must specify a callback Id and then/catch.";

return true;
}

auto callbackId = arguments[0]->GetIntValue();

if (callbackId == 0)
{
exception = "Invalid callback Id";

return true;
}

auto success = arguments[1]->GetBoolValue();

auto response = CefProcessMessage::Create(kEvaluateJavascriptResponse);

auto responseArgList = response->GetArgumentList();
//Success
responseArgList->SetBool(0, success);
//Callback Id
SetInt64(responseArgList, 1, callbackId);
if (exception == "")
{
if (success)
{
SerializeV8Object(arguments[2], responseArgList, 2, nullptr);
}
else
{
auto reason = arguments[2];
responseArgList->SetString(2, reason->GetStringValue());
}
}
else
{
responseArgList->SetString(2, exception);
}

auto context = CefV8Context::GetCurrentContext();

auto frame = context->GetFrame();

frame->SendProcessMessage(CefProcessId::PID_BROWSER, response);

return false;
}

IMPLEMENT_REFCOUNTING(JavascriptPromiseHandler);
};
}
2 changes: 1 addition & 1 deletion CefSharp.BrowserSubprocess.Core/Wrapper/Frame.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -165,7 +165,7 @@ void Frame::ExecuteJavaScriptAsync(String^ code, String^ scriptUrl, int startLin
_frame->ExecuteJavaScript(StringUtils::ToNative(code), StringUtils::ToNative(scriptUrl), startLine);
}

Task<JavascriptResponse^>^ Frame::EvaluateScriptAsync(String^ script, String^ scriptUrl, int startLine, Nullable<TimeSpan> timeout)
Task<JavascriptResponse^>^ Frame::EvaluateScriptAsync(String^ script, String^ scriptUrl, int startLine, Nullable<TimeSpan> timeout, bool useImmediatelyInvokedFuncExpression)
{
throw gcnew NotImplementedException();
}
Expand Down
2 changes: 1 addition & 1 deletion CefSharp.BrowserSubprocess.Core/Wrapper/Frame.h
Original file line number Diff line number Diff line change
Expand Up @@ -164,7 +164,7 @@ namespace CefSharp
/*--cef(optional_param=script_url)--*/
virtual void ExecuteJavaScriptAsync(String^ code, String^ scriptUrl, int startLine);

virtual Task<JavascriptResponse^>^ EvaluateScriptAsync(String^ script, String^ scriptUrl, int startLine, Nullable<TimeSpan> timeout);
virtual Task<JavascriptResponse^>^ EvaluateScriptAsync(String^ script, String^ scriptUrl, int startLine, Nullable<TimeSpan> timeout, bool useImmediatelyInvokedFuncExpression);

///
// Returns true if this is the main (top-level) frame.
Expand Down
7 changes: 6 additions & 1 deletion CefSharp.Core/Internals/CefFrameWrapper.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -225,7 +225,7 @@ void CefFrameWrapper::ExecuteJavaScriptAsync(String^ code, String^ scriptUrl, in
_frame->ExecuteJavaScript(StringUtils::ToNative(code), StringUtils::ToNative(scriptUrl), startLine);
}

Task<JavascriptResponse^>^ CefFrameWrapper::EvaluateScriptAsync(String^ script, String^ scriptUrl, int startLine, Nullable<TimeSpan> timeout)
Task<JavascriptResponse^>^ CefFrameWrapper::EvaluateScriptAsync(String^ script, String^ scriptUrl, int startLine, Nullable<TimeSpan> timeout, bool useImmediatelyInvokedFuncExpression)
{
ThrowIfDisposed();
ThrowIfFrameInvalid();
Expand All @@ -246,6 +246,11 @@ Task<JavascriptResponse^>^ CefFrameWrapper::EvaluateScriptAsync(String^ script,
//create a new taskcompletionsource
auto idAndComplectionSource = pendingTaskRepository->CreatePendingTask(timeout);

if (useImmediatelyInvokedFuncExpression)
{
script = "(function() { let cefSharpInternalCallbackId = " + idAndComplectionSource.Key + "; " + script + " })();";
}

auto message = CefProcessMessage::Create(kEvaluateJavascriptRequest);
auto argList = message->GetArgumentList();
SetInt64(argList, 0, idAndComplectionSource.Key);
Expand Down
2 changes: 1 addition & 1 deletion CefSharp.Core/Internals/CefFrameWrapper.h
Original file line number Diff line number Diff line change
Expand Up @@ -165,7 +165,7 @@ namespace CefSharp
/*--cef(optional_param=script_url)--*/
virtual void ExecuteJavaScriptAsync(String^ code, String^ scriptUrl, int startLine);

virtual Task<JavascriptResponse^>^ EvaluateScriptAsync(String^ script, String^ scriptUrl, int startLine, Nullable<TimeSpan> timeout);
virtual Task<JavascriptResponse^>^ EvaluateScriptAsync(String^ script, String^ scriptUrl, int startLine, Nullable<TimeSpan> timeout, bool useImmediatelyInvokedFuncExpression);

///
// Returns true if this is the main (top-level) frame.
Expand Down
28 changes: 28 additions & 0 deletions CefSharp.Test/OffScreen/OffScreenBrowserBasicFacts.cs
Original file line number Diff line number Diff line change
Expand Up @@ -199,6 +199,34 @@ public async Task CanEvaluateScriptAsyncWithEncodedStringArguments()
}
}

[Theory]
[InlineData("return 42;", true, "42")]
[InlineData("return new Promise(function(resolve, reject) { resolve(42); });", true, "42")]
[InlineData("return new Promise(function(resolve, reject) { reject('reject test'); });", false, "reject test")]
public async Task CanEvaluateScriptAsPromiseAsync(string script, bool success, string expected)
{
using (var browser = new ChromiumWebBrowser("http://www.google.com"))
{
await browser.LoadPageAsync();

var mainFrame = browser.GetMainFrame();
Assert.True(mainFrame.IsValid);

var javascriptResponse = await browser.EvaluateScriptAsPromiseAsync(script);

Assert.Equal(success, javascriptResponse.Success);

if (success)
{
Assert.Equal(expected, javascriptResponse.Result.ToString());
}
else
{
Assert.Equal(expected, javascriptResponse.Message);
}
}
}

[Fact]
public async Task CanMakeFrameUrlRequest()
{
Expand Down
6 changes: 5 additions & 1 deletion CefSharp/IFrame.cs
Original file line number Diff line number Diff line change
Expand Up @@ -124,8 +124,12 @@ public interface IFrame : IDisposable
/// <param name="scriptUrl">is the URL where the script in question can be found, if any.</param>
/// <param name="startLine">is the base line number to use for error reporting.</param>
/// <param name="timeout">The timeout after which the Javascript code execution should be aborted.</param>
/// <param name="useImmediatelyInvokedFuncExpression">When true the script is wrapped in a self executing function.
/// Make sure to use a return statement in your javascript. e.g. (function () { return 42; })();
/// When false don't include a return statement e.g. 42;
/// </param>
/// <returns>A Task that can be awaited to perform the script execution</returns>
Task<JavascriptResponse> EvaluateScriptAsync(string script, string scriptUrl = "about:blank", int startLine = 1, TimeSpan? timeout = null);
Task<JavascriptResponse> EvaluateScriptAsync(string script, string scriptUrl = "about:blank", int startLine = 1, TimeSpan? timeout = null, bool useImmediatelyInvokedFuncExpression = false);

/// <summary>
/// Returns true if this is the main (top-level) frame.
Expand Down
Loading