小程序开发中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);
  
  ...
}
相关推荐
jinanwuhuaguo29 分钟前
OpenClaw 2026年4月升级大系深度解读剖析:从“架构重塑”到“信任内建”的范式跃迁
android·开发语言·人工智能·架构·kotlin·openclaw
huhy~1 小时前
基于Ubuntu 24.04 LTS 搭建OpenStack F 版
android·ubuntu·openstack
2401_885885041 小时前
视频短信接口接入麻不麻烦?API调用说明
android·音视频
lI-_-Il2 小时前
喜马拉雅 v9.4.56.3:移动端全站音频资源畅听版
android·音视频
我命由我123452 小时前
Android Jetpack Compose - SearchBar(搜索栏)、Tab(标签页)、时间选择器、TooltipBox(工具提示)
android·java·java-ee·kotlin·android studio·android jetpack·android-studio
恋猫de小郭3 小时前
Flutter PC 多窗口最新进展,底层原生窗口句柄支持已合并
android·前端·flutter
sp423 小时前
NativeScript 的 Jetpack Compose 入门指南
android·android jetpack
用户69371750013843 小时前
AI来了,同事们的效率为什么差这么多?
android·前端·ai编程
凡小烦3 小时前
从定制化页签tab到compose列表使用
android·前端
kekegdsz3 小时前
高丢包、高延迟、断网秒切:开源一个 Android 弱网测试利器
android·测试