• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2025 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 #include "web_message_port.h"
16 #include "../../../ohos_interface/ohos_glue/base/include/ark_web_errno.h"
17 
18 namespace OHOS {
19 namespace NWeb {
20 namespace {
21 constexpr int INIT_ERROR = -2;
22 }
WebMessagePort(int32_t nwebId,std::string & port,bool isExtentionType)23 WebMessagePort::WebMessagePort(int32_t nwebId, std::string& port, bool isExtentionType)
24     : nwebId_(nwebId), portHandle_(port), isExtentionType_(isExtentionType)
25 {}
26 
ClosePort()27 ErrCode WebMessagePort::ClosePort()
28 {
29     auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
30     if (!nweb_ptr) {
31         return INIT_ERROR;
32     }
33 
34     nweb_ptr->ClosePort(portHandle_);
35     portHandle_.clear();
36     return NWebError::NO_ERROR;
37 }
38 
PostPortMessage(std::shared_ptr<NWebMessage> data,std::shared_ptr<NWebRomValue> value)39 ErrCode WebMessagePort::PostPortMessage(std::shared_ptr<NWebMessage> data, std::shared_ptr<NWebRomValue> value)
40 {
41     auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
42     if (!nweb_ptr) {
43         return INIT_ERROR;
44     }
45 
46     if (portHandle_.empty()) {
47         WVLOG_E("can't post message, message port already closed");
48         return NWebError::CAN_NOT_POST_MESSAGE;
49     }
50     nweb_ptr->PostPortMessageV2(portHandle_, value);
51     if (ArkWebGetErrno() != RESULT_OK) {
52         nweb_ptr->PostPortMessage(portHandle_, data);
53     }
54     return NWebError::NO_ERROR;
55 }
56 
SetPortMessageCallback(std::shared_ptr<NWebMessageValueCallback> callback)57 ErrCode WebMessagePort::SetPortMessageCallback(
58     std::shared_ptr<NWebMessageValueCallback> callback)
59 {
60     auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
61     if (!nweb_ptr) {
62         return INIT_ERROR;
63     }
64 
65     if (portHandle_.empty()) {
66         WVLOG_E("can't register message port callback event, message port already closed");
67         return NWebError::CAN_NOT_REGISTER_MESSAGE_EVENT;
68     }
69     nweb_ptr->SetPortMessageCallback(portHandle_, callback);
70     return NWebError::NO_ERROR;
71 }
72 
GetPortHandle() const73 std::string WebMessagePort::GetPortHandle() const
74 {
75     return portHandle_;
76 }
77 
78 } // namespace NWeb
79 } // namespace OHOS