菜单

ABlog

Github
文章漫游 切换到深色模式 切换到浅色模式

uTools API #

在插件应用初始化完成时,uTools 会自动在你的 window 对象上挂载 utools 对象。

事件 #

你可以根据需要,事先定义好一些回调函数,uTools 会在事件产生时主动调用它们。

onPluginEnter(callback) #

进入插件应用时,uTools 将会主动调用这个方法。

示例 #

utools.onPluginEnter(({ code, type, payload, option }) => {
  console.log("用户进入插件应用", code, type, payload);
});

/*
type 为 "files" 时, payload 值示例
[
	{
		"isFile": true,
		"isDirectory": false,
		"name": "demo.js",
		"path": "C:\\demo.js"
	}
]

type 为 "window" 时, payload 值示例
{
	"id": 264584,
	"class": "Chrome_WidgetWin_1",
	"title": "demo",
	"x": -8,
	"y": -8,
	"width": 1936,
	"height": 1056,
	"appPath": "C:\\demo.exe",
	"pid": 232,
	"app": "demo.exe"
}

type 为 "img" 时, payload 值示例
data:image/png;base64,...

type 为 "text"、"regex"、 "over" 时, payload 值为进入插件应用时的主输入框文本
*/

onMainPush(callback, selectCallback) #

向搜索面板推送消息(需要 feature.mainPush 设置为 true)

示例 #

function callback({ code, type, payload }) {
  return [
    {
      icon: "icon.png",
      text: "选项1",
      title: "help text",
    },
    {
      text: "选项2",
      anyField: "xxxx",
    },
  ];
}
function selectCallback({ code, type, payload, option }) {
  if (option.xxx) {
    // 返回 true 表示需要进入插件应用处理
    return true;
  }
  // 不进入插件应用 "执行粘贴文本"
  utools.hideMainWindowPasteText(option.text);
}
utools.onMainPush(callback, selectCallback);

onPluginOut(callback) #

插件应用退出时,uTools 将会主动调用这个方法。

示例 #

utools.onPluginOut((processExit) => {
  if (processExit) {
    console.log("插件应用完全退出");
  } else {
    console.log("插件应用隐藏后台");
  }
});

onPluginDetach(callback) #

用户对插件应用进行分离操作时,uTools 将会主动调用这个方法。

示例 #

utools.onPluginDetach(() => {
  console.log("插件应用已作为系统窗口使用");
});

onDbPull(callback) #

当此插件应用的数据在其他设备上被更改后同步到此设备时,uTools 将会主动调用这个方法

示例 #

utools.onDbPull(() => {
  console.log("onDbPull");
});

窗口交互 #

hideMainWindow(isRestorePreWindow) #

执行该方法将会隐藏 uTools 主窗口,包括此时正在主窗口运行的插件应用,分离的插件应用不会被隐藏。

示例 #

utools.hideMainWindow();

showMainWindow() #

执行该方法将会显示 uTools 主窗口,包括此时正在主窗口运行的插件应用。

示例 #

utools.showMainWindow();

setExpendHeight(height) #

执行该方法将会修改插件应用窗口的高度。

示例 #

utools.setExpendHeight(100);

setSubInput(onChange, placeholder, isFocus) #

设置子输入框,进入插件应用后,原本 uTools 的搜索条主输入框将会变成子输入框,子输入框可以为插件应用所使用。

main.png

主输入框

main.png

子输入框

示例 #

utools.setSubInput(({ text }) => {
  console.log(text);
}, "搜索");

removeSubInput() #

移除已经设置的子输入框,在插件应用切换到其他页面时可以重新设置子输入框为其所用。

示例 #

utools.removeSubInput();

setSubInputValue(value) #

直接对子输入框的值进行设置。

示例 #

utools.setSubInputValue("uTools");

subInputFocus() #

子输入框获得焦点

示例 #

utools.subInputFocus();

subInputSelect() #

子输入框获得焦点并选中

示例 #

utools.subInputSelect();

subInputBlur() #

子输入框失去焦点,插件应用获得焦点

示例 #

utools.subInputBlur();

outPlugin() #

执行该方法将会退出当前插件应用。(插件应用进入后台,进程并未结束)

示例 #

utools.outPlugin();

redirect(label, payload) #

该方法可以携带数据,跳转到另一个插件应用进行处理,如果用户未安装对应的插件应用将引导进入插件应用市场下载。

示例 #

// 跳转到插件应用「聚合翻译」并翻译内容
utools.redirect(["聚合翻译", "翻译"], "hello world");

// 找到 “翻译” 关键字,并自动跳转到对应插件应用
utools.redirect("翻译", "hello world");

// 跳转到插件应用「OCR 文字识别」并识别图片中文字
utools.redirect(["OCR 文字识别", "OCR 文字识别"], {
  type: "img",
  data: "data:image/png;base64,", // base64
});

// 跳转到插件应用「JSON 编辑器」查看 Json 文件
utools.redirect(["JSON 编辑器", "Json"], {
  type: "files",
  data: "/path/test.json", // 支持数组
});

showOpenDialog(options) #

弹出文件选择框

示例 #

utools.showOpenDialog({
  filters: [{ name: "plugin.json", extensions: ["json"] }],
  properties: ["openFile"],
});

showSaveDialog(options) #

弹出文件保存框

示例 #

utools.showSaveDialog({
  title: "保存位置",
  defaultPath: utools.getPath("downloads"),
  buttonLabel: "保存",
});

findInPage(text, options) #

插件应用页面中查找内容

示例 #

utools.findInPage("utools");

stopFindInPage(action) #

停止插件应用页面中查找

示例 #

utools.stopFindInPage();

startDrag(file) #

原生拖拽文件到其他窗口

示例 #

utools.startDrag("/path/to/file");

createBrowserWindow(url, options, callback) #

创建浏览器窗口

示例 #

const ubWindow = utools.createBrowserWindow(
  "test.html",
  {
    show: false,
    title: "测试窗口",
    webPreferences: {
      preload: "preload.js",
    },
  },
  () => {
    // 显示
    ubWindow.show();
    // 置顶
    ubWindow.setAlwaysOnTop(true);
    // 窗口全屏
    ubWindow.setFullScreen(true);
    // 向子窗口传递数据
    ubWindow.webContents.send("ping");
    require("electron").ipcRenderer.sendTo(ubWindow.webContents.id, "ping");
    // 执行脚本
    ubWindow
      .executeJavaScript(
        'fetch("https://jsonplaceholder.typicode.com/users/1").then(resp => resp.json())'
      )
      .then((result) => {
        console.log(result); // Will be the JSON object from the fetch call
      });
  }
);
console.log(ubWindow);
// 在新建窗口 JavaScript 中接收父窗口传递过来的数据
const { ipcRenderer } = require("electron");
ipcRenderer.on("ping", (event, data) => {
  console.log(event);
  console.log(data);
});

isDarkColors() #

是否深色模式

示例 #

utools.onPluginEnter(({ code, type, payload }) => {
  document.body.className = utools.isDarkColors() ? "dark-mode" : "";
});

动态增减功能 #

很多时候,插件应用中会提供一些功能供用户进行个性化设置(例如:网页快开 插件应用),这部分配置无法在 plugin.json 事先定义好,所以我们提供了以下方法对插件应用功能进行动态增减。

getFeatures(codes) #

获取插件应用动态创建的功能。

// 获取所有动态功能
const features = utools.getFeatures();
console.log(features);
// 获取特定 code
const features = utools.getFeatures(["code-1", "code-2"]);
console.log(features);

setFeature(feature) #

为本插件应用动态新增某个功能。

utools.setFeature({
  code: "hosts",
  explain: "hosts切换",
  // "icon": "res/xxx.png",
  // "icon": "data:image/png;base64,xxx...",
  // "platform": ["win32", "darwin", "linux"]
  cmds: ["hosts"],
});

removeFeature(code) #

动态删除本插件应用的某个功能。

utools.removeFeature("code");

用户 #

获取当前用户头像、昵称

getUser() #

获取当前用户,未登录账号返回 null

console.log(utools.getUser());

fetchUserServerTemporaryToken() #

获取用户服务端临时令牌,用于获取用户基础信息接口

utools.fetchUserServerTemporaryToken().then((ret) => {
  console.log(ret);
});

付费 #

isPurchasedUser() #

是否付费用户,返回 true 表示永久授权,返回 "yyyy-mm-dd hh:mm:ss" 表示授权到期时间

if (utools.isPurchasedUser()) {
  // 已付费的合法用户,可使用插件应用完整功能
}

openPurchase(options, callback) #

打开付费 (软件付费模式)

utools.openPurchase({ goodsId: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" }, () => {
  // 购买完成,解锁全部功能
});

openPayment(options, callback) #

打开支付(服务付费模式)

utools.openPayment({ goodsId: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" }, () => {
  // 用户完成支付
});

fetchUserPayments() #

获取用户支付记录

utools.fetchUserPayments().then((ret) => {
  console.log(ret);
  /**
  	    {
        "order_id": "ZsVSwEDoR7PPs6vWdAGplEpEpNjn8xb4", // utools 订单号
        "out_order_id": "", // 外部订单号
        "open_id": "a331127d654761ac91d086b942aae7b6", uTools 用户 ID, 对于此插件应用不变且唯一
        "pay_fee": 1, // 支付金额(分)
        "body": "会员1年", // 支付内容
        "attach": "", // 附加数据
        "goods_id": "6n193s7P95p9gA13786YkwQ5oxHpVW4f", // 商品 ID
        "paid_at": "2021-06-18 16:55:26", // 支付时间
        "created_at": "2021-06-18 16:55:11" // 订单生成时间
    }
  */
});

输入 #

hideMainWindowPasteFile(file) #

粘贴文件

示例 #

utools.hideMainWindowPasteFile("/path/to/file");

hideMainWindowPasteImage(img) #

粘贴图像

示例 #

// 路径
utools.hideMainWindowPasteImage("/path/to/img.png");
// base64
utools.hideMainWindowPasteImage("data:image/png;base64,xxxxxxxxx");

hideMainWindowPasteText(text) #

粘贴文本

示例 #

utools.hideMainWindowPasteText("Hi, uTools");

hideMainWindowTypeString(text) #

输入字符串(输入法原理)

示例 #

// 输入一句文本
utools.hideMainWindowTypeString("uTools 新一代效率工具平台 - 🐼👏🦄👨‍👩‍👧‍👦🚵🏻");

工具 #

屏幕取色 & 屏幕截图

screenColorPick(callback) #

屏幕取色

示例 #

utools.screenColorPick(({ hex, rgb }) => {
  console.log(hex); // #FFFFFF
  console.log(rgb); // RGB(0, 0, 0)
});

screenCapture(callback) #

屏幕截图

示例 #

utools.screenCapture((base64Str) => {
  utools.redirect("识别图片中文字", { type: "img", data: base64Str });
});

模拟 #

模拟敲击键盘 和 鼠标点击

simulateKeyboardTap(key, ...modifier) #

模拟键盘按键

示例 #

// 模拟键盘敲击 Enter
utools.simulateKeyboardTap("enter");
// windows linux 模拟粘贴
utools.simulateKeyboardTap("v", "ctrl");
// macos 模拟粘贴
utools.simulateKeyboardTap("v", "command");
// 模拟 Ctrl + Alt + A
utools.simulateKeyboardTap("a", "ctrl", "alt");

simulateMouseMove(x, y) #

模拟鼠标移动

示例 #

utools.simulateMouseMove(100100)

simulateMouseClick(x, y) #

模拟鼠标左键单击

示例 #

utools.simulateMouseClick(100100)

simulateMouseRightClick(x, y) #

模拟鼠标右键单击

示例 #

utools.simulateMouseRightClick(100100)

simulateMouseDoubleClick(x, y) #

模拟鼠标双击

示例 #

utools.simulateMouseDoubleClick(100100)

屏幕 #

getCursorScreenPoint() #

获取鼠标绝对位置

示例 #

const point = utools.getCursorScreenPoint();
console.log(point.x, point.y);

getPrimaryDisplay() #

获取主显示器

示例 #

const display = utools.getPrimaryDisplay();
console.log(display);

getAllDisplays() #

获取所有显示器

示例 #

const displays = utools.getAllDisplays();
console.log(displays);

getDisplayNearestPoint(point) #

获取位置所在的显示器

示例 #

const display = utools.getDisplayNearestPoint({ x: 100, y: 100 });
console.log(display);

getDisplayMatching(rect) #

获取矩形所在的显示器

示例 #

const display = utools.getDisplayMatching({
  x: 100,
  y: 100,
  width: 200,
  height: 200,
});
console.log(display);

desktopCaptureSources(options) #

录屏源 参考 Electron API desktopCapturer getSourcesopen in new window

示例 #

(async () => {
  const ousrces = await utools.desktopCaptureSources({
    types: ["window", "screen"],
  });
  const stream = await navigator.mediaDevices.getUserMedia({
    audio: false,
    video: {
      mandatory: {
        chromeMediaSource: "desktop",
        chromeMediaSourceId: ousrces[0].id,
        minWidth: 1280,
        maxWidth: 1280,
        minHeight: 720,
        maxHeight: 720,
      },
    },
  });
  const video = document.querySelector("video");
  video.srcObject = stream;
  video.onloadedmetadata = (e) => video.play();
})();

复制 #

copyFile(file) #

复制文件到系统剪贴板

示例 #

// 复制单个文件
utools.copyFile("/path/to/file");
// 复制多个文件
utools.copyFile(["/path/to/file1", "/path/to/file2"]);

copyImage(img) #

复制图片到系统剪贴板

示例 #

// 路径
utools.copyImage("/path/to/img.png");
// base64
utools.copyImage("data:image/png;base64,xxxxxxxxx");

copyText(text) #

复制文本

示例 #

utools.copyText("Hi, uTools");

getCopyedFiles() #

获取复制的文件或文件夹

示例 #

utools.getCopyedFiles();
// 返回 [{ isFile: true, isDirectory: false, name: 'test.png', path: '/path/to/test.png' }]

系统 #

showNotification(body, clickFeatureCode) #

显示系统通知

示例 #

utools.showNotification("Hi, uTools");

shellOpenPath(fullPath) #

系统默认方式打开给定的文件

示例 #

utools.shellOpenPath("/path/to/file");

shellShowItemInFolder(fullPath) #

系统文件管理器中显示给定的文件

示例 #

utools.shellShowItemInFolder("/path/to/file");

shellOpenExternal(url) #

系统默认的协议打开 URL

示例 #

// 浏览器打开
utools.shellOpenExternal("https://u.tools");

shellBeep() #

播放哔哔声

示例 #

utools.shellBeep();

getNativeId() #

获取本地 ID

示例 #

// 存储只与当前设备相关的信息
const nativeId = utools.getNativeId();
utools.dbStorage.setItem(nativeId + "/key", "native value");

getAppName() #

获取软件名称

示例 #

console.log(utools.getAppName());

getAppVersion() #

获取软件版本

示例 #

console.log(utools.getAppVersion());

getPath(name) #

获取路径

示例 #

// 获取下载路径
console.log(utools.getPath("downloads"));

getFileIcon(filePath) #

获取文件图标

示例 #

// 获取扩展名为 "txt" 的文件图标
utools.getFileIcon(".txt");
// 获取文件夹图标
utools.getFileIcon("folder");
// 获取文件图标
utools.getFileIcon("D:\\test.url");

readCurrentFolderPath() #

读取当前文件管理器窗口路径 (linux 不支持)

示例 #

utools.readCurrentFolderPath().then((dir) => {
  console.log(dir);
});

readCurrentBrowserUrl() #

读取当前浏览器窗口 URL (linux 不支持)

MacOS 支持浏览器 Safari、Chrome、Microsoft Edge、Opera、Vivaldi、Brave

Windows 支持浏览器 Chrome、Firefox、Edge、IE、Opera、Brave

示例 #

utools.readCurrentBrowserUrl().then((url) => {
  console.log(url);
});

isDev() #

判断插件应用是否在开发环境

示例 #

if (utools.isDev()) {
  console.log("coding");
}

isMacOS() #

是否 MacOS 操作系统

示例 #

if (utools.isMacOS()) {
  console.log("mac");
}

isWindows() #

是否 Windows 操作系统

示例 #

if (utools.isWindows()) {
  console.log("windows");
}

isLinux() #

是否 Linux 操作系统

示例 #

if (utools.isLinux()) {
  console.log("linux");
}