named_message_port_connector_fuchsia.cc 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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 "fuchsia_web/runners/cast/named_message_port_connector_fuchsia.h"
  5. #include <fuchsia/mem/cpp/fidl.h>
  6. #include <fuchsia/web/cpp/fidl.h>
  7. #include <memory>
  8. #include <string>
  9. #include <utility>
  10. #include <vector>
  11. #include "base/files/file_util.h"
  12. #include "base/fuchsia/mem_buffer_util.h"
  13. #include "base/logging.h"
  14. #include "base/path_service.h"
  15. #include "components/cast/named_message_port_connector/grit/named_message_port_connector_resources.h"
  16. namespace {
  17. constexpr uint64_t kPortConnectorBindingsId = 1000;
  18. } // namespace
  19. NamedMessagePortConnectorFuchsia::NamedMessagePortConnectorFuchsia(
  20. fuchsia::web::Frame* frame)
  21. : frame_(frame) {
  22. DCHECK(frame_);
  23. base::FilePath port_connector_js_path;
  24. CHECK(base::PathService::Get(base::DIR_ASSETS, &port_connector_js_path));
  25. port_connector_js_path = port_connector_js_path.AppendASCII(
  26. "components/cast/named_message_port_connector/"
  27. "named_message_port_connector.js");
  28. std::string bindings_script_string;
  29. CHECK(
  30. base::ReadFileToString(port_connector_js_path, &bindings_script_string));
  31. DCHECK(!bindings_script_string.empty())
  32. << "NamedMessagePortConnector resources not loaded.";
  33. // Inject the JS connection API into the Frame.
  34. constexpr char kBindingsScriptVmoName[] = "port-connector-js";
  35. fuchsia::mem::Buffer bindings_script = base::MemBufferFromString(
  36. std::move(bindings_script_string), kBindingsScriptVmoName);
  37. std::vector<std::string> origins = {"*"};
  38. frame_->AddBeforeLoadJavaScript(
  39. kPortConnectorBindingsId, std::move(origins), std::move(bindings_script),
  40. [](fuchsia::web::Frame_AddBeforeLoadJavaScript_Result result) {
  41. CHECK(result.is_response())
  42. << "Couldn't inject port connector bindings.";
  43. });
  44. }
  45. NamedMessagePortConnectorFuchsia::~NamedMessagePortConnectorFuchsia() {
  46. // Nothing to do if there is no attached Frame.
  47. if (!frame_)
  48. return;
  49. frame_->RemoveBeforeLoadJavaScript(kPortConnectorBindingsId);
  50. }
  51. void NamedMessagePortConnectorFuchsia::DetachFromFrame() {
  52. frame_ = nullptr;
  53. }