js_runner.h 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. // Copyright 2017 The Chromium Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file.
  4. #ifndef EXTENSIONS_RENDERER_BINDINGS_JS_RUNNER_H_
  5. #define EXTENSIONS_RENDERER_BINDINGS_JS_RUNNER_H_
  6. #include <memory>
  7. #include "base/callback.h"
  8. #include "v8/include/v8.h"
  9. namespace extensions {
  10. // A helper class to execute JS functions safely.
  11. class JSRunner {
  12. public:
  13. // Returns the instance of the JSRunner for the specified |context|.
  14. static JSRunner* Get(v8::Local<v8::Context> context);
  15. // Sets the instance for a given |context|.
  16. static void SetInstanceForContext(v8::Local<v8::Context> context,
  17. std::unique_ptr<JSRunner> runner);
  18. // Clears the instance for a given |context|.
  19. static void ClearInstanceForContext(v8::Local<v8::Context> context);
  20. virtual ~JSRunner() {}
  21. // Called with the result of executing the function, as well as the context
  22. // it was executed in. Note: This callback is *not* guaranteed to be invoked
  23. // (and won't be if, for instance, the context is destroyed before this is
  24. // ran).
  25. // NOTE(devlin): We could easily change that if desired.
  26. using ResultCallback = base::OnceCallback<void(v8::Local<v8::Context>,
  27. v8::MaybeLocal<v8::Value>)>;
  28. // Calls the given |function| in the specified |context| and with the provided
  29. // arguments. JS may be executed asynchronously if it has been suspended in
  30. // the context.
  31. void RunJSFunction(v8::Local<v8::Function> function,
  32. v8::Local<v8::Context> context,
  33. int argc,
  34. v8::Local<v8::Value> argv[]);
  35. // Same as above, but if a |callback| is provided, it will be called with the
  36. // results of the function running.
  37. virtual void RunJSFunction(v8::Local<v8::Function> function,
  38. v8::Local<v8::Context> context,
  39. int argc,
  40. v8::Local<v8::Value> argv[],
  41. ResultCallback callback) = 0;
  42. // Executes the given |function| synchronously and returns the result. This
  43. // should *only* be called in direct response to script running, since it
  44. // bypasses script suspension.
  45. virtual v8::MaybeLocal<v8::Value> RunJSFunctionSync(
  46. v8::Local<v8::Function> function,
  47. v8::Local<v8::Context> context,
  48. int argc,
  49. v8::Local<v8::Value> argv[]) = 0;
  50. // Sets a global instance for testing that will be returned instead of the
  51. // per-context version (if any).
  52. static void SetInstanceForTesting(JSRunner* runner);
  53. // Returns the global testing instance.
  54. static JSRunner* GetInstanceForTesting();
  55. };
  56. } // namespace extensions
  57. #endif // EXTENSIONS_RENDERER_BINDINGS_JS_RUNNER_H_