小程序开发中ios和安卓问题

一、 onUnload 不能再调用 editorCtx.getContents

项目场景:

笔记页面使用富文本,在笔记中记载后返回时,要提示新建笔记成功toast


问题描述

安卓可以提示toast,但是ios不行。

js 复制代码
  async onUnload() {
    try {
      await this.checkAndHandleEmptyNote();
    } catch (error) {
      console.error('onUnload error:', error);
    }

    if (this.debounceTimer) {
      clearTimeout(this.debounceTimer);
    }
  },
    async checkAndHandleEmptyNote() {
     // 获取当前editor中的纯文本内容
    let textContent = '';
    if (this.editorCtx) {
      try {
        textContent = await new Promise((resolve) => {
          this.editorCtx.getContents({
            success: (res) => {
              resolve(res.text || TextUtils.htmlToText(res.html || ''));
            },
            fail: () => {
              resolve(TextUtils.htmlToText(this.data.content));
            }
          });
        });
      } catch (error) {
        textContent = TextUtils.htmlToText(this.data.content);
      }
    } else {
      textContent = TextUtils.htmlToText(this.data.content);
    }
    const isEmpty = !this.data.title.trim() && !textContent.trim();
    if (this.data.delete) {
      this.refreshNoteListPage();
      return;
    }
    if (isEmpty && this.data.isNewNote && this.data.id != '0') {
      this.deleteEmptyNoteDirectly();
    } else if (this.data.isContentModified) {
      // 有内容的笔记,先同步到服务器,然后刷新列表
      if (this.data.isNewNote) {
        wx.showToast({
          title: '笔记创建成功',
          icon: 'none'
        })
      }
      this.syncToServer().then(() => {
        this.refreshNoteListPage();
      });
    }
  },

原因分析:

刚开始以为是因为iOS 小程序在 onUnload 中调用 wx.showToast 不生效,但是通过调试后发现,isEmpty并没有输出. --> 执行流程被中断了,中断点只可能在editorCtx.getContents 这行。

onUnload 调用这一段,iOS 会直接中断 editorCtx 的任何异步操作。
包括 getContents,不会执行 success 或 fail → Promise 不 resolve → 函数永远卡住

富文本编辑器 editorCtx 异步 API 在 onUnload 内不可靠,尤其 iOS 会直接不执行。


解决方案:

进入 onUnload 前,把 editor 内容保存到 data。

js 复制代码
onContentInput(e) {
  let plainText = e.detail.text;
  this.data.latestText = plainText; // <-- 新增缓存
}

async checkAndHandleEmptyNote() {
  const text = this.data.latestText || '';

  const isEmpty = !this.data.title.trim() && !text.trim();
  console.log('isEmpty', isEmpty);
  
  ...
}
相关推荐
Mr YiRan5 小时前
网络请求API监控与网络切换埋点
android·网络
美狐美颜sdk9 小时前
直播APP开发技术栈详解:视频美颜SDK、人脸识别与实时渲染
android·人工智能·音视频·美颜sdk·直播美颜sdk
HouWan14 小时前
Swift 6.4 发布:iOS开发者值得关注的新特性
ios·swift·apple
奈斯先生Vector14 小时前
当模型版本不断变化,RelayRouter 能否帮助 AI 应用摆脱深度绑定
android·java·人工智能·开源·aigc
TimeFine14 小时前
让强模型做“总工”,让高性价比模型写代码
android
用户380341658829715 小时前
macOS 录屏:ScreenCaptureKit 与 iOS 的分野,共用引擎的抽象层该切在哪
ios·音视频开发
又见情义16 小时前
RK3568 Android 13 屏蔽 healthd 电池日志经验分享
android
HouWan16 小时前
Flutter iOS UISceneDelegate 迁移指南:理清新的 Scene 生命周期
flutter·ios·app
00后程序员张16 小时前
Xcode vs KXApp,体积差几十G,选轻量方案还是完整工具链?
ide·vscode·ios·objective-c·个人开发·swift·敏捷流程
古法安卓19 小时前
Android-Fork 机制详解
android·java·android studio