web_message_reply_proxy_impl.cc 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. // Copyright 2020 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 "weblayer/browser/js_communication/web_message_reply_proxy_impl.h"
  5. #include <memory>
  6. #include "base/android/jni_android.h"
  7. #include "base/android/jni_string.h"
  8. #include "weblayer/browser/java/jni/WebMessageReplyProxyImpl_jni.h"
  9. #include "weblayer/browser/page_impl.h"
  10. #include "weblayer/public/js_communication/web_message.h"
  11. #include "weblayer/public/js_communication/web_message_reply_proxy.h"
  12. namespace weblayer {
  13. WebMessageReplyProxyImpl::WebMessageReplyProxyImpl(
  14. int id,
  15. base::android::ScopedJavaGlobalRef<jobject> client,
  16. const std::string& origin_string,
  17. bool is_main_frame,
  18. WebMessageReplyProxy* reply_proxy)
  19. : reply_proxy_(reply_proxy) {
  20. auto* env = base::android::AttachCurrentThread();
  21. java_object_ = Java_WebMessageReplyProxyImpl_create(
  22. env, reinterpret_cast<intptr_t>(this), id, client, is_main_frame,
  23. base::android::ConvertUTF8ToJavaString(env, origin_string),
  24. static_cast<PageImpl&>(reply_proxy->GetPage()).java_page());
  25. }
  26. WebMessageReplyProxyImpl::~WebMessageReplyProxyImpl() {
  27. Java_WebMessageReplyProxyImpl_onNativeDestroyed(
  28. base::android::AttachCurrentThread(), java_object_);
  29. }
  30. void WebMessageReplyProxyImpl::PostMessage(
  31. JNIEnv* env,
  32. const base::android::JavaParamRef<jstring>& message_contents) {
  33. auto message = std::make_unique<WebMessage>();
  34. base::android::ConvertJavaStringToUTF16(env, message_contents,
  35. &(message->message));
  36. reply_proxy_->PostWebMessage(std::move(message));
  37. }
  38. bool WebMessageReplyProxyImpl::IsActive(JNIEnv* env) {
  39. return !reply_proxy_->IsInBackForwardCache();
  40. }
  41. void WebMessageReplyProxyImpl::OnPostMessage(
  42. std::unique_ptr<WebMessage> message) {
  43. auto* env = base::android::AttachCurrentThread();
  44. Java_WebMessageReplyProxyImpl_onPostMessage(
  45. env, java_object_,
  46. base::android::ConvertUTF16ToJavaString(env, message->message));
  47. }
  48. void WebMessageReplyProxyImpl::OnBackForwardCacheStateChanged() {
  49. Java_WebMessageReplyProxyImpl_onActiveStateChanged(
  50. base::android::AttachCurrentThread(), java_object_);
  51. }
  52. } // namespace weblayer