文章目录
- 场景
- 源代码
- 功能实现
- 点击在页面上出现裁剪框
- 百度云文字识别
- 复制选中
- 参考

场景
因为学习通题目都加密了复制过来也无法进行搜题 无奈写了这个插件
为什么使用插件的形式 而不是脚本 ?
使用了html2canvas结果是比的是dom文字变成了加密过的 无法识别 于是使用chrome的截屏API结合html2cnavas实现截取文字 并交由百度云进行文字识别
源代码
https://gitee.com/honbingitee/capture-ocr
功能实现
点击在页面上出现裁剪框
只是看起来这样而已😄 实际上是这几部实现的
- 调用chrome截屏API – 截取的是全屏 而不是部分 没有找到自由选择的API
- 截取到的全屏图片生成img 传给html2canvs
- html2canvas默认不是全屏并且周围有透明区域不符合通过更改源代码实现 可参考 Cropper不显示透明背景超出图片的部分 AND Cropper初始化时设置裁剪框的位置和宽高
- 将html2canvas浮动到最上层显示
popup.js
调用chrome截屏API
chrome.tabs.captureVisibleTab(null, {}, function (base64) {//发送到 content_script.js sendMessageToContentScript({ type: 'get_screenshot_data', payload: base64 }, (response) => {console.log("response:", response);});});
content_script.js
chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {switch (request.type) {case 'test': {console.log("test 接收到");sendResponse("test接收成功");break;}case 'get_screenshot_data': {sendResponse("接收成功");const base64 = request.payload;if (!base64) return sendResponse("未收到有效数据");sendResponse("接收成功");console.log("接收到了截屏数据");//触发事件发送截屏数据执行下一步const event = new CustomEvent('handleScreenshot', { detail: { base64 } })window.top.document.dispatchEvent(event);...
content_script.js
可以访问页面
百度云文字识别
百度云文字识别
复制选中
const selectText = getSelection().toString().trim().replace(/\n/g, "");if (!selectText) return console.warn('未获取选中内容');const isCopySuccess = copyToClipboard(selectText);if (isCopySuccess) {log("复制成功:", selectText);}
function copyToClipboard(text) {if (window.clipboardData && window.clipboardData.setData) {//@ts-ignorereturn window.clipboardData.setData("Text", text);} else if (document.queryCommandSupported && document.queryCommandSupported("copy")) {var textarea = document.createElement("textarea");textarea.textContent = text;textarea.style.position = "fixed"; // Prevent scrolling to bottom of page in Microsoft Edge.document.body.appendChild(textarea);textarea.select();try {return document.execCommand("copy"); // Security exception may be thrown by some browsers.} catch (ex) {warn("Copy to clipboard failed.", ex);return false;} finally {document.body.removeChild(textarea);}}}
参考
Chrome插件(扩展)开发全攻略
chrome文档