js_reply_proxy.cc 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. // Copyright (c) 2019 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. #include "android_webview/browser/js_java_interaction/js_reply_proxy.h"
  5. #include "android_webview/browser_jni_headers/JsReplyProxy_jni.h"
  6. #include "base/android/jni_string.h"
  7. #include "components/js_injection/browser/web_message.h"
  8. #include "components/js_injection/browser/web_message_reply_proxy.h"
  9. namespace android_webview {
  10. JsReplyProxy::JsReplyProxy(js_injection::WebMessageReplyProxy* reply_proxy)
  11. : reply_proxy_(reply_proxy) {
  12. JNIEnv* env = base::android::AttachCurrentThread();
  13. java_ref_.Reset(
  14. Java_JsReplyProxy_create(env, reinterpret_cast<intptr_t>(this)));
  15. }
  16. JsReplyProxy::~JsReplyProxy() {
  17. if (!java_ref_)
  18. return;
  19. JNIEnv* env = base::android::AttachCurrentThread();
  20. Java_JsReplyProxy_onDestroy(env, java_ref_);
  21. }
  22. base::android::ScopedJavaLocalRef<jobject> JsReplyProxy::GetJavaPeer() {
  23. return base::android::ScopedJavaLocalRef<jobject>(java_ref_);
  24. }
  25. void JsReplyProxy::PostMessage(
  26. JNIEnv* env,
  27. const base::android::JavaParamRef<jstring>& message) {
  28. std::unique_ptr<js_injection::WebMessage> web_message =
  29. std::make_unique<js_injection::WebMessage>();
  30. web_message->message = base::android::ConvertJavaStringToUTF16(env, message);
  31. reply_proxy_->PostWebMessage(std::move(web_message));
  32. }
  33. } // namespace android_webview