当前位置:网站首页>TinyMCE series (III) introduction to common TinyMCE APIs
TinyMCE series (III) introduction to common TinyMCE APIs
2022-06-12 11:43:00 【Jioho_】
List of articles
- tinymce Commonly used API Introduce
- Introduce modules
- Register plug-ins
- Get the parameters passed in by the editor
- Event monitoring and distribution
- tinymce Built in request
- Dynamically add resources
- Getting and manipulating dom node and operation html
- Get the cursor selection
- Save snapshots ( Undo and redo )
- Execute built-in instructions
- Register your own instructions
- Insert and set content
- Last
tinymce Commonly used API Introduce
This article will introduce the commonly used API, For the following example code , Many use one editor The variable of . Be careful editor Is the current instance , Instead of global variables , If you need to use global variables, use tinymce.activeEditor
editor Usually from PluginManager.add After registering the plug-in , Callback parameters will carry editor example
Introduce modules
tinymce.util.Tools.resolve
- Original document tinymce.util.tools
- For modules that can be introduced, refer to the documentation API Reference part
The reference code is excerpted from :tinymce Of fullpage plug-in unit
var global = tinymce.util.Tools.resolve('tinymce.PluginManager')
var global$1 = tinymce.util.Tools.resolve('tinymce.util.Tools')
var global$2 = tinymce.util.Tools.resolve('tinymce.html.DomParser')
var global$3 = tinymce.util.Tools.resolve('tinymce.html.Node')
var global$4 = tinymce.util.Tools.resolve('tinymce.html.Serializer')
If not used util.Tools.resolve introduce , Some functions can also be realized through tinymce.PluginManager Call directly
Register plug-ins
PluginManager.add(‘ The plug-in name ’, function(editor,path){})
- Original document :tinymce.plugin
| Parameters | effect |
|---|---|
| editor | Get current tinymce example |
| path | Get the currently loaded URL( Relative tinymce The network path of , It is mainly used to load other additional resources ) |
* editor Object as the current tinymce Examples of are very important , Include event bindings in the current plug-in , Get the configuration of the current instance
* editor Equate to tinymce.activeEditor or tinymce.get(‘my_editor’)
The official example is as follows , stay add Button registration in the callback method of , Logical binding, etc
In addition to the basic buttons , The drop-down menu , There are also many built-in form types , See document for details tinymce.editor.ui.registry
tinymce.PluginManager.add('MyPlugin', function(editor, url) {
// Register a toolbar button that triggers an alert when clicked
// To show this button in the editor, include it in the toolbar setting
editor.ui.registry.addButton('myCustomToolbarButton', {
text: 'My Custom Button',
onAction: function() {
alert('Button clicked!')
}
})
// Register a menu item that triggers an alert when clicked
// To show this menu item in the editor, include it in the menu setting
editor.ui.registry.addMenuItem('myCustomMenuItem', {
text: 'My Custom Menu Item',
onAction: function() {
alert('Menu item clicked')
}
})
// Either return plugin metadata or do not return
return {
name: 'MyPlugin',
url: 'https://mydocs.com/myplugin'
}
})
Get the parameters passed in by the editor
editor.getParam
- Original document : getparam
getParma receive 2 Parameters
- The name of the configuration variable to get
- Get the default value when it is not available
Parameters are passed in tinymce.init Method , Like passing in a myvalue Parameters :
In business code
tinymce.init({
selector: 'textarea.tinymce',
myvalue: {
key: 'value' } // The arguments here are of any type , It can be for string、 Callback functions, etc ( The callback function suggests to trigger by means of events )
})
Plug in logic , Use getParam To obtain parameters
// If you want to use editor Must be in tinymce.PluginManager.add Call back to get editor example
var someval = editor.getParam('myvalue', {
key: '1' })
// If you want to get parameters elsewhere , have access to tinymce The editor that currently gets the focus gets the instance
var someval1 = tinymce.activeEditor.getParam('myvalue', {
key: '1' })
// You can also specify tinymce The node of ID obtain (textarea.tinymce Namely class be known as tinymce Of textarea label )
var someval2 = tinymce.get('textarea.tinymce').getParam('myvalue')
Event monitoring and distribution
editor.fire() and editor.on()
- Original document tinymce.util.observable
The events after distribution are in the business logic , Or you can listen in different plug-ins , You can only get editor The instance can be monitored everywhere
The incident was distributed : adopt editor.fire(' Event name ', Parameter values )
Event monitoring : After the event is dispatched , adopt editor.on(' Event name ', Callback function ) monitor
Realize local event dispatch :
Reference use tinymce.util.eventdispatcher
var eventDispatcher = new EventDispatcher()
eventDispatcher.on('click', function() {
console.log('data')
})
eventDispatcher.fire('click', {
data: 123 })
tinymce Built in request
It is suggested to complete the request through the business logic , Avoid making requests in plug-ins
JSON request
- Original document tinymce.util.jsonrequest
var json = new tinymce.util.JSONRequest({
url: 'somebackend.php',
params: ['a', 'b'],
success: function(result) {
console.dir(result)
}
})
XHR request
- Original document tinymce.util.xhr
// Sends a low level Ajax request
tinymce.util.XHR.send({
url: 'someurl',
success: function(text) {
console.debug(text)
}
})
// Add custom header to XHR request
tinymce.util.XHR.on('beforeSend', function(e) {
e.xhr.setRequestHeader('X-Requested-With', 'Something')
})
JSONP request It is not listed in detail in the document , stay tinymce.js You can see the relevant logic in the source code
JSONP Although by adding script Request from tag , However, the corresponding resource ID will be added to the underlying parameters , So you can use callback Find the parameter value corresponding to the issued request
tinymce JSONP Source code implementation part :
var JSONP = {
callbacks: {
},
count: 0,
send: function(settings) {
var self = this,
dom = DOMUtils$1.DOM,
count = settings.count !== undefined ? settings.count : self.count
var id = 'tinymce_jsonp_' + count
self.callbacks[count] = function(json) {
dom.remove(id)
delete self.callbacks[count]
settings.callback(json)
}
dom.add(dom.doc.body, 'script', {
id: id,
src: settings.url,
type: 'text/javascript'
})
self.count++
}
}
JSONP Use... In plug-ins , Send a request
const $jsonp = tinymce.util.Tools.resolve('tinymce.util.JSONP')
$jsonp.send({
url: 'someurl',
callback: function(json) {
resolve(json)
}
})
Dynamically add resources
Sometimes there will be dynamic loading JS, Or dynamically load style requirements
tinymce Sometimes through iframe Form embedding of , Use it directly document.body The inserted resources cannot affect iframe Content , So you need to use the built-in API Add
Dynamic loading JStinymce.dom.scriptloader
// Load a script from a specific URL using the global script loader
tinymce.ScriptLoader.load('somescript.js')
// Load a script using a unique instance of the script loader
var scriptLoader = new tinymce.dom.ScriptLoader()
scriptLoader.load('somescript.js')
// Load multiple scripts
var scriptLoader = new tinymce.dom.ScriptLoader()
scriptLoader.add('somescript1.js')
scriptLoader.add('somescript2.js')
scriptLoader.add('somescript3.js')
scriptLoader.loadQueue(function() {
alert('All scripts are now loaded.')
})
By adding dom Node mode add tinymce.dom.domutils
tinymce.activeEditor.dom.add(tinymce.activeEditor.getBody(), 'script', {
src: 'somescript4.js',
type: 'text/javascript'
})
Getting and manipulating dom node and operation html
operation dom Use built-in as much as possible DomQuery Wait and so on API, Because sometimes tinymce It's through iframe Form embedding of , ordinary document.querySelector You may not be able to find the corresponding dom, The inserted resources cannot affect iframe Content
If you want to use document.querySelector Isogenesis API, Use tinymce.activeEditor.getBody() or editor.doc Replace document.
editor.doc.querySelector('.my_plugin') // Get to the editor .my_plugin The node of
tinymce.activeEditor.getBody() or editor.doc Always point to tinymce Of dom example
- obtain dom node , More applicable to existing dom node , You need to manipulate the contents of the node
tinymce Similar offers JQ The function of . But no JQ So perfect , The use method can be directly through $ = tinymce.dom.DomQuery Or use $ = tinymce.util.Tools.resolve('tinymce.dom.DomQuery')
- html operation , More applicable to the resolution of string types to dom type
hold HTML String parsing html node tinymce.html.domparser
hold HTML Parsing a single node tinymce.html.node
Get the cursor selection
The selected text will have 2 Case , In the comments of the code . Code section check zk_quick_style part
relevant API file :
Cursor operation : tinymce.dom.selection
The function is to put the selected text / If it is not selected, wrap the text in a specified style
/** * Get the selected content * @param {*} editor */
function getRangeText(editor = tinymce.activeEditor) {
let rngInfo = editor.selection.getRng()
let rangeText = rngInfo.commonAncestorContainer.textContent
if (!rangeText) {
return ''
}
// This is because if there is 3 Paragraph text , Select 2 During the period ,commonAncestorContainer The text of is actually giving 3 Segment merged text
// But the selection range is the position calculated according to the first paragraph of text and the last paragraph of text , So start matching according to the beginning text
let _startText = rngInfo.startContainer.textContent
rangeText = rangeText.replace(new RegExp(`.*(${
_startText}.*)`), '$1')
let _start = rngInfo.startOffset
let _end = rngInfo.endOffset
let _select = _end - _start
if (_select == 0 || _select == rangeText.length) {
// situation 1:_select == 0 No text is selected , Then put the current div All the texts are put forward , Just go by default , And create a selection , Select the text
// situation 2: In the same line , All the words are selected , At this time, you should also select the node of his superior , Otherwise use insert There will be one more blank line on the top when
editor.selection.select(rngInfo.commonAncestorContainer)
} else {
// If there is a selection , And consider the case of multiple rows , _end What is recorded is the character selected in the last line , Not the entire length of the cursor
let _endText = rngInfo.endContainer.textContent
rangeText = rangeText.replace(new RegExp(`(.*)${
_endText}`), '$1')
rangeText += _endText.substring(0, _end)
rangeText = rangeText.substring(_start, rangeText.length)
}
return rangeText
}
Save snapshots ( Undo and redo )
Original document :tinymce.undomanager
If you want to record the operation after some operation steps, you can cancel it , You can use the following commands
editor.undoManager.add()
Execute built-in instructions
Instruction documents execcommand
web There are also built-in instructions in MDN-execCommand, But it's time to API Has been abandoned , Although it may be possible to call ( Unclear compatibility ), Recommend or use tinymce Sealed execCommand Execute instructions
For common In bold , In the middle Wait for the operation .web There is a set of instructions ,tinymce On this basis, it also encapsulates unique instructions , The call method is as follows :
// Example
editor.execCommand(' Instruction names ')
// Left alignment instruction
editor.execCommand('JustifyLeft')
// In the middle
editor.execCommand('JustifyCenter')
The common instructions collected are as follows :
| Instruction names | effect |
|---|---|
| bold | In bold |
| italic | Italics |
| subscript | Subscript |
| superscript | Superscript |
| strikeThrough | Delete line |
| underline | Underline |
| insertOrderedList | Insert sequence table |
| insertUnorderedList | Insert unordered list |
| justifyCenter | In the middle |
| justifyFull | Align around |
| justifyLeft | Align left |
| justifyRight | Right alignment |
| insertHorizontalRule | Insert the level bar |
The document does not list many material names , However, you can find the instructions you want to execute by looking at the source code , stay tinymce.js Search for EditorCommands.prototype.setupCommands You can see most of the instructions and implementations
Register your own instructions
The related documents : addcommand
The code comes from the example on the official website :
Registered a company called mycommand Instructions . The effect is through Built in windowManager eject The currently selected text
editor.addCommand('mycommand', function(ui, v) {
editor.windowManager.alert('Hello world!! Selection: ' + editor.selection.getContent({
format: 'text' }))
})
// Execution instruction
editor.execCommand('mycommand')
Insert and set content
Namely setContent and insertContent
editor.setContent(`<p> Set the entire editor content to this text </p>`)
editor.insertContent(`<p> Inserts the current text at the current position of the cursor </p>`)
Last
tinymce frequently-used API It's about the above , Time monitoring has been covered , obtain dom node , Cursor operation , Internal instructions, etc .
Only have API Still not enough , The next chapter will cover tinymce Common built-in UI Component is introduced
边栏推荐
- Socket Programming TCP
- ARM指令集之跳转指令
- Lambda and filter, List 和 numpy array的索引,以及各种距离指标distance-metrics,拼接数组以及axis=0 and axis=1的区分
- NVIDIA Jetson Nano Developer Kit 入门
- Design of tablewithpage
- ARM指令集之Load/Store访存指令(二)
- UML series articles (31) architecture modeling - deployment diagram
- 文件夹目录结构自动生成
- PIP install in the CONDA environment cannot be installed into the specified CONDA environment (the default PIP installation location of the CONDA environment)
- 视频分类的类间和类内关系——正则化
猜你喜欢

6.6 分離卷積

Ficusjs series (I) introduction to ficusjs

【藍橋杯單片機 國賽 第十一届】

manuscript手稿格式准备

Les humains veulent de l'argent, du pouvoir, de la beauté, de l'immortalité, du bonheur... Mais les tortues ne veulent être qu'une tortue.

Unlimited growth, we will all go to the future | the 15th anniversary of the founding of InfoQ China

VirtualBox 虚拟机因系统异常关机虚拟机启动项不见了

Node crawler puppeter usage

7-5 复数四则运算

【蓝桥杯单片机 国赛 第十一届】
随机推荐
如何查看glibc版本
ARM指令集之杂类指令
【蓝桥杯单片机 国赛 第十一届】
Lambda表达式 | 浅解
Inter class and intra class relations in video classification -- regularization
Socket Programming TCP
MySQL lock leak detection and defect filling
UML series articles (30) architecture modeling -- product diagram
LVS health state detection based on application layer
[Blue Bridge Cup SCM 11th National race]
十折交叉验证代码中的问题
視頻分類的類間和類內關系——正則化
mysql的悲观锁和乐观锁
ioremap
35. search insertion position
Basic principle of Doppler effect
一个人必须不停地写作,才能不被茫茫人海淹没。
套接字实现 TCP 通信流程
ARM指令集之伪指令
【藍橋杯單片機 國賽 第十一届】