You've already forked joplin
mirror of
https://github.com/laurent22/joplin.git
synced 2025-06-24 23:26:50 +02:00
Plugins: Added support for bi-directional messages in content scripts and webview scripts using postMessage
This commit is contained in:
@ -1,8 +1,9 @@
|
||||
import { PluginStates } from '../reducer';
|
||||
import { ContentScriptType } from '../api/types';
|
||||
import { ContentScriptType, ContentScriptContext, PostMessageHandler } from '../api/types';
|
||||
import { dirname } from '@joplin/renderer/pathUtils';
|
||||
import shim from '../../../shim';
|
||||
import Logger from '../../../Logger';
|
||||
import PluginService from '../PluginService';
|
||||
|
||||
const logger = Logger.create('loadContentScripts');
|
||||
|
||||
@ -12,6 +13,17 @@ export interface ExtraContentScript {
|
||||
assetPath: string;
|
||||
}
|
||||
|
||||
function postMessageHandler(pluginId: string, scriptType: ContentScriptType, contentScriptId: string): PostMessageHandler {
|
||||
return (message: any) => {
|
||||
if (scriptType === ContentScriptType.MarkdownItPlugin) {
|
||||
logger.error('context.postMessage is not available to renderer content scripts');
|
||||
} else {
|
||||
const plugin = PluginService.instance().pluginById(pluginId);
|
||||
return plugin.emitContentScriptMessage(contentScriptId, message);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
export function contentScriptsToRendererRules(plugins: PluginStates): ExtraContentScript[] {
|
||||
return loadContentScripts(plugins, ContentScriptType.MarkdownItPlugin);
|
||||
}
|
||||
@ -35,7 +47,14 @@ function loadContentScripts(plugins: PluginStates, scriptType: ContentScriptType
|
||||
const module = shim.requireDynamic(contentScript.path);
|
||||
if (!module.default || typeof module.default !== 'function') throw new Error(`Content script must export a function under the "default" key: Plugin: ${pluginId}: Script: ${contentScript.id}`);
|
||||
|
||||
const loadedModule = module.default({});
|
||||
const context: ContentScriptContext = {
|
||||
pluginId,
|
||||
contentScriptId: contentScript.id,
|
||||
postMessage: postMessageHandler(pluginId, contentScript.id),
|
||||
};
|
||||
|
||||
const loadedModule = module.default(context);
|
||||
|
||||
if (!loadedModule.plugin && !loadedModule.codeMirrorResources && !loadedModule.codeMirrorOptions) throw new Error(`Content script must export a "plugin" key or a list of CodeMirror assets or define a CodeMirror option: Plugin: ${pluginId}: Script: ${contentScript.id}`);
|
||||
|
||||
output.push({
|
||||
|
Reference in New Issue
Block a user