1. 背景
运营给产品提了个需求:后台 CMS 配置的文档下载等超链接,希望登录后才能打开(用于拉新用户),我来实现:
- 方案1:类似 link,开发一个新等 tinymce 插件
- 方案2:新的菜单按钮,是否新窗口打开
- 方案3:使用 link 的 rel 属性 http://tinymce.ax-z.cn/plugins/link.php
2. tinymce 配置
<!-- vue tmpl or pure html -->
<tiny-mce v-model="content" :init="config" @onChange="change" />
// config.js
export default {
theme: 'modern',
fontsize_formats: '8px 10px 12px 14px 16px 18px 20px 22px 24px 26px 39px 34px 38px 42px 48px',
plugins: 'autoresize print preview fullpage searchreplace autolink directionality visualblocks visualchars fullscreen image link media template codesample table charmap hr pagebreak nonbreaking anchor toc insertdatetime advlist lists textcolor wordcount imagetools contextmenu colorpicker textpattern code paste',
menubar: 'file edit insert view format table',
toolbar1: 'fontsizeselect | formatselect | bold italic strikethrough forecolor backcolor | link | alignleft aligncenter alignright alignjustify | numlist bullist outdent indent | removeformat anchor image-upload media-upload baike-link kefu-link fullscreen',
image_advtab: true,
language: 'zh_CN',
content_css: '/mce.css', // 自定义 css 显示效果
paste_auto_cleanup_on_paste: true,
paste_remove_styles: true,
paste_remove_styles_if_webkit: true,
paste_strip_class_attributes: true,
autoresize_max_height: 500,
autoresize_min_height: 100,
autoresize_on_init: true,
autoresize_bottom_margin: 10,
autoresize_overflow_padding: 10,
// http://tinymce.ax-z.cn/plugins/link.php
link_context_toolbar: false,
// link_class_list: [
// { title: '无', value: '' },
// { title: '需登录', value: 'need-login' },
// ],
rel_list: [
{ title: '不判断登录', value: '' },
{ title: '需登录后查看', value: 'need-login' },
],
};
/* mce.css */
a.mce-item-anchor {
width: auto !important;
height: auto !important;
margin: 0 5px;
padding: 0 2px 0 10px;
background-position: 2px center !important;
}
a.mce-item-anchor:after {
content: attr(id);
color: #F08;
}
a.mce-item-anchor:before {
content: attr(name);
color: #F80;
}
.mce-content-body table {
border-collapse: collapse;
}
.prettyprint {
overflow: overlay;
}
[rel="need-login"]:before {
content: "🔒";
}
不知不觉我添加了好几个自定义配置/插件:插入链接、插入百科、插入视频、插入图片、客服链接、锚点显示等
3. 文档查看
// 注册监听事件
document.body.addEventListener('click', function addEvent(e: Event) {
let dom: HTMLElement = e && e.target as HTMLElement;
while (dom && dom.tagName && dom.getAttribute && dom.tagName !== 'BODY') {
const href = (dom as HTMLLinkElement).href;
if (dom.getAttribute('rel') === 'need-login') { // 下载判断
const username = getLoginNameFromCookie(); // TODO: 自己实现 getLoginNameFromCookie
if (!username) {
e.preventDefault();
showLoginDialog(function (rst: any) { // TODO: 自己实现 showLoginDialog
if (rst && +rst.code === 200) {
location.href = href;
}
});
}
break;
}
dom = dom.parentNode as HTMLElement;
}
});
效果:
<a href="http://tinymce.ax-z.cn/plugins/link.php" rel="need-login">测试登录后查看</a>