I want to add keyboard shortcuts to the button in tinymce editor. The problem is that I don't have access to the source code of the website. So this needs to be done using userscript(i.e tampermonkey, greasemonkey).
I have successfully created a script that added the shortcuts if I execute the script form the console available in the development tools of the browser, but this code does not work in tampermonkey or greasemonkey. The script is as follows:
function simulate(element, eventName)
{
var options = extend(defaultOptions, arguments[2] || {});
var oEvent, eventType = null;
for (var name in eventMatchers)
{
if (eventMatchers[name].test(eventName)) { eventType = name; break; }
}
if (!eventType)
throw new SyntaxError('Only HTMLEvents and MouseEvents interfaces are supported');
if (document.createEvent)
{
oEvent = document.createEvent(eventType);
if (eventType == 'HTMLEvents')
{
oEvent.initEvent(eventName, options.bubbles, options.cancelable);
}
else
{
oEvent.initMouseEvent(eventName, options.bubbles, options.cancelable, document.defaultView,
options.button, options.pointerX, options.pointerY, options.pointerX, options.pointerY,
options.ctrlKey, options.altKey, options.shiftKey, options.metaKey, options.button, element);
}
element.dispatchEvent(oEvent);
}
else
{
options.clientX = options.pointerX;
options.clientY = options.pointerY;
var evt = document.createEventObject();
oEvent = extend(evt, options);
element.fireEvent('on' + eventName, oEvent);
}
return element;
}
function extend(destination, source) {
for (var property in source)
destination[property] = source[property];
return destination;
}
var eventMatchers = {
'HTMLEvents': /^(?:load|unload|abort|error|select|change|submit|reset|focus|blur|resize|scroll)$/,
'MouseEvents': /^(?:click|dblclick|mouse(?:down|up|over|move|out))$/
}
var defaultOptions = {
pointerX: 0,
pointerY: 0,
button: 0,
ctrlKey: false,
altKey: false,
shiftKey: false,
metaKey: false,
bubbles: true,
cancelable: true
}
tinymce.activeEditor.on('keydown', function(e) {
var e = e || window.event; // for IE to cover IEs window object
if(e.altKey && e.which == 81) { //Alt + Q
//alert('Keyboard shortcut working!');
simulate(document.evaluate('//div[@id="mceu_3"]/button', document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue, "click");
return false;
}
});
In the above code div[@id="mceu_3"]/button
is the div
tag that contain the button to be triggered by the key combination.
Could any one please provide a solution, also I don't have much knowledge of tinymce editor, so a simplified explanation will be more helpful.
Thanks in advance.
After searching for another day, finally I found the solution to my query here.
tinymce.activeEditor.on('keyup', function(e) {
console.debug("keyup");
});