UNPKG

fastchar-dom-plugin

Version:

Chrome插件,用于操作HTML的DOM

136 lines (135 loc) 4.41 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.FastPopup = void 0; /** * 插件popup页面操作工具类,在插件的popup页面中引用本工具类,可直接操作内容页面的DOM结构! */ var FastPopup; (function (FastPopup) { /** * 内容页面核心操作 */ class Core { static connectPort; static popupId; static callbackMap = {}; static started = false; constructor() { Core.popupId = Core.buildUDID(); } /** * 构建唯一标识符 * @private */ static buildUDID() { let d = new Date().getTime(); return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) { let r = (d + Math.random() * 16) % 16 | 0; d = Math.floor(d / 16); return (c == 'x' ? r : (r & 0x3 | 0x8)).toString(16); }); } /** * 开始发起连接 */ static startConnect() { this.started = true; chrome.tabs.query({ active: true }, function (tab) { // @ts-ignore FastPopup.Core.connectPort = chrome.tabs.connect(tab[0].id, { name: "FastCharPopup@" }); FastPopup.Core.connectPort.onMessage.addListener(function (msg) { if (msg.event && msg.event === "OnReturnMethod") { FastPopup.Core.returnMethod(msg); } }); }); } /** * 发送消息 * @param data * @private */ static postMessage(data) { if (!this.started) { Core.startConnect(); } if (this.connectPort) { this.connectPort.postMessage(data); } } /** * 执行方法 * @param data * @param callback */ static invokeMethod(data, callback) { data["event"] = "OnInvokeMethod"; data["popupId"] = Core.popupId; data["callbackId"] = this.buildUDID(); this.callbackMap[data.callbackId] = callback; this.postMessage(data); } /** * 响应方法 * @param msg */ static returnMethod(msg) { if (msg.callbackId && this.callbackMap[msg.callbackId]) { this.callbackMap[msg.callbackId](msg.data); } } } FastPopup.Core = Core; /** * 内容页面Element操作 */ class Element { /** * 获取节点的网页内容 * @param selector jquery选择器 * @param callback 回调函数 */ static getHtml(selector, callback) { Core.invokeMethod({ method: "html", selectors: [selector], params: [] }, callback); } /** * 获取节点的文本内容 * @param selector jquery选择器 * @param callback 回调函数 */ static getText(selector, callback) { Core.invokeMethod({ method: "text", selectors: [selector], params: [] }, callback); } /** * 设置目标节点value值 * @param selector jquery选择器 * @param value 设置的值 * @param callback 回调函数 */ static setValue(selector, value, callback) { Core.invokeMethod({ method: "val", selectors: [selector], params: [value] }, callback); } /** * 获取目标节点的value值 * @param selector jquery选择器 * @param callback 回调函数 */ static getValue(selector, callback) { Core.invokeMethod({ method: "val", selectors: [selector], params: [] }, callback); } /** * 点击目标节点 * @param selector jquery选择器 * @param callback 回调函数 */ static click(selector, callback) { Core.invokeMethod({ method: "click", selectors: [selector], params: [] }, callback); } } FastPopup.Element = Element; for (let subClass in FastPopup) { // @ts-ignore FastPopup[subClass](); } window["FastPopup"] = FastPopup; })(FastPopup = exports.FastPopup || (exports.FastPopup = {}));