1 // Copyright 2021 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #ifndef PDF_POST_MESSAGE_RECEIVER_H_
6 #define PDF_POST_MESSAGE_RECEIVER_H_
10 #include "base/memory/raw_ptr.h"
11 #include "base/memory/scoped_refptr.h"
12 #include "base/memory/weak_ptr.h"
13 #include "base/values.h"
14 #include "gin/interceptor.h"
15 #include "gin/public/wrapper_info.h"
16 #include "gin/wrappable.h"
17 #include "v8/include/v8.h"
20 class SequencedTaskRunner;
24 class ObjectTemplateBuilder;
27 namespace chrome_pdf {
29 class V8ValueConverter;
31 // Implements the `postMessage()` API exposed to the plugin embedder. The
32 // received messages are converted and forwarded to the `Client`.
33 // `PostMessageReceiver`'s lifetime is managed by the V8 garbage collector,
34 // meaning it can outlive the `Client`. Messages are dropped if the `Client` is
36 class PostMessageReceiver final : public gin::Wrappable<PostMessageReceiver>,
37 public gin::NamedPropertyInterceptor {
39 // The interface for a plugin client that handles messages from its embedder.
42 // Handles converted messages from the embedder.
43 virtual void OnMessage(const base::Value::Dict& message) = 0;
50 static gin::WrapperInfo kWrapperInfo;
52 // Creates a scriptable object with an implemented `postMessage()` method.
53 // Messages are posted asynchronously to `client` using `client_task_runner`.
54 static v8::Local<v8::Object> Create(
56 base::WeakPtr<V8ValueConverter> v8_value_converter,
57 base::WeakPtr<Client> client,
58 scoped_refptr<base::SequencedTaskRunner> client_task_runner);
60 PostMessageReceiver(const PostMessageReceiver&) = delete;
61 PostMessageReceiver& operator=(const PostMessageReceiver&) = delete;
64 ~PostMessageReceiver() override;
69 base::WeakPtr<V8ValueConverter> v8_value_converter,
70 base::WeakPtr<Client> client,
71 scoped_refptr<base::SequencedTaskRunner> client_task_runner);
74 gin::ObjectTemplateBuilder GetObjectTemplateBuilder(
75 v8::Isolate* isolate) override;
76 const char* GetTypeName() override;
78 // gin::NamedPropertyInterceptor:
79 v8::Local<v8::Value> GetNamedProperty(v8::Isolate* isolate,
80 const std::string& property) override;
81 std::vector<std::string> EnumerateNamedProperties(
82 v8::Isolate* isolate) override;
84 // Lazily creates and retrieves `function_template_`.
85 v8::Local<v8::FunctionTemplate> GetFunctionTemplate();
87 // Implements the `postMessage()` method called by the embedder.
88 void PostMessage(v8::Local<v8::Value> message);
90 base::WeakPtr<V8ValueConverter> v8_value_converter_;
92 v8::Persistent<v8::FunctionTemplate> function_template_;
94 raw_ptr<v8::Isolate> isolate_;
96 base::WeakPtr<Client> client_;
98 scoped_refptr<base::SequencedTaskRunner> client_task_runner_;
100 base::WeakPtrFactory<PostMessageReceiver> weak_factory_{this};
103 } // namespace chrome_pdf
105 #endif // PDF_POST_MESSAGE_RECEIVER_H_