内容目录
安装 tampermonkey
编写js插件
// ==UserScript==
// @name Paste Image to Markdown
// @namespace http://tampermonkey.net/
// @version 1.1
// @description Paste images as Markdown links by uploading to the image server
// @author Your Name
// @match https://blog.xin-hao.top/wp-admin/post-new.php
// @grant GM_xmlhttpRequest
// ==/UserScript==
(function() {
'use strict';
document.addEventListener('paste', function(event) {
let items = (event.clipboardData || event.originalEvent.clipboardData).items;
for (let index in items) {
let item = items[index];
if (item.kind === 'file') {
let blob = item.getAsFile();
if (blob && blob.type.startsWith('image/')) {
uploadImage(blob);
}
}
}
});
function uploadImage(blob) {
let formData = new FormData();
formData.append('image', blob);
formData.append('uid', 4); // 添加其他所需参数
GM_xmlhttpRequest({
method: 'POST',
url: 'https://img.xin-hao.top/api/update',
data: formData,
onload: function(response) {
if (response.status === 200) {
let jsonResponse = JSON.parse(response.responseText);
let imageUrl = "https://img.xin-hao.top" + jsonResponse.data.original.url;
insertMarkdownImage(imageUrl);
} else {
console.error('Image upload failed:', response);
}
},
onerror: function(response) {
console.error('Image upload error:', response);
},
headers: {
'Accept': 'application/json'
}
});
}
function insertMarkdownImage(imageUrl) {
let markdownImage = `![图片](${imageUrl})`;
console.log(markdownImage);
insertAtCursor(markdownImage);
}
function insertAtCursor(text) {
let activeElement = document.activeElement;
if (activeElement && (activeElement.tagName === 'TEXTAREA' || (activeElement.tagName === 'INPUT' && activeElement.type === 'text'))) {
let start = activeElement.selectionStart;
let end = activeElement.selectionEnd;
activeElement.value = activeElement.value.substring(0, start) + text + activeElement.value.substring(end);
activeElement.selectionStart = activeElement.selectionEnd = start + text.length;
activeElement.focus();
} else {
document.execCommand('insertText', false, text);
}
}
})();
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END
暂无评论内容