/** * UniApp APP 邮件模板适配器 * 适用于 cwg-rich-text 组件展示邮件内容 * rich-text组件对HTML支持有限,需要简化处理 * @param {string} html - 原始邮件HTML字符串 * @returns {string} - 适配后的HTML字符串 */ export function adaptCWGEmailForUniApp(html) { if (!html || typeof html !== 'string') return ''; let result = html; // ============================================== // 1. 【修复HTML语法错误】处理不规范的标签 // ============================================== // 修复 的问题 - 移除斜杠后的空格 result = result.replace(/]*?)\s*\/\s*style=/gi, ']*?)>/gi, function (match, attrs) { // 提取现有样式 const styleMatch = attrs.match(/style=["']([^"']*)["']/i); let existingStyle = styleMatch ? styleMatch[1] : ''; // 添加响应式样式 let newStyle = existingStyle; // 确保样式末尾有分号 if (newStyle && !newStyle.endsWith(';')) { newStyle += ';'; } // 添加缺失的样式 if (!existingStyle.includes('max-width')) { newStyle += 'max-width:100%;'; } if (!existingStyle.includes('height:')) { newStyle += 'height:auto;'; } if (!existingStyle.includes('display:')) { newStyle += 'display:block;'; } // 移除多余的分号 newStyle = newStyle.replace(/;;+/g, ';'); if (styleMatch) { return match.replace(/style=["']([^"']*)["']/i, `style="${newStyle}"`); } else { // 确保标签正确闭合 if (attrs.trim().endsWith('/')) { return ``; } else { return ``; } } }); // ============================================== // 4. 【容器适配】移除大尺寸固定宽度限制 // ============================================== result = result.replace(/style="([^"]*?)width:\s*(\d+)px([^"]*?)"/gi, function (match, before, width, after) { // 保留小尺寸的宽度(如logo等),只处理大尺寸 if (parseInt(width) > 200) { let newStyle = `${before}width:100%;max-width:${width}px;${after}`; newStyle = newStyle.replace(/;;+/g, ';'); return `style="${newStyle}"`; } return match; }); // ============================================== // 5. 【清理多余分号】修复样式中的双分号问题 // ============================================== result = result.replace(/style="([^"]*)"/gi, function (_, style) { return `style="${style.replace(/;;+/g, ';').replace(/;$/, '')}"`; }); // ============================================== // 6. 【修复特殊字符】处理HTML实体 // ============================================== result = result.replace(/’/g, "'"); result = result.replace(/ /g, ' '); result = result.replace(/&/g, '&'); // ============================================== // 7. 【移除script/style标签】rich-text不支持 // ============================================== result = result.replace(//gi, ''); result = result.replace(//gi, ''); // ============================================== // 8. 【简化标签】移除rich-text不支持的标签 // ============================================== // 移除HTML文档结构标签 result = result.replace(/<\/?html[^>]*>/gi, ''); result = result.replace(/<\/?head[^>]*>/gi, ''); result = result.replace(/<\/?body[^>]*>/gi, ''); result = result.replace(/]*>/gi, ''); result = result.replace(/]*>/gi, ''); // ============================================== // 9. 【添加内联样式包装】确保容器不溢出 // ============================================== result = `
${result}
`; return result; }