Chrome擴展實現網頁圖片右鍵上傳(以E站圖片搜索為例)


近期有一個需求,客戶要對其他網頁中看到的圖片在E站的搜圖引擎里進行查詢,但E站的搜索引擎只支持本地圖片上傳,客戶需要先把圖片保存到本地再上傳比較麻煩。於是希望能有更快速的方法完成整個查詢過程。在經過一番研究后,使用Chrome擴展完成了客戶的需求。

首先對E站的圖片搜索抓包,發現是一個Content-type為multipart/form-data的POST行為,POST內容即為圖片的二進制數據,Response為一個302重定向,到搜索結果頁面。Charles抓包結果如下:

 

 

於是確定總體思路:利用Chrome擴展的contextMenus配置右鍵菜單(對Chrome右鍵擴展開發不熟悉的推薦參考這篇文章),並為contentx為image的元素類型綁定post上傳動作。實現的難點在於如何從<img>標簽里拿到圖片的二進制數據,話不多說,直接上代碼:

 1 /* background.js */
 2 /* 其他文件代碼略 */
 3 
 4 var ehentaiquery = chrome.contextMenus.create({"title": 'Ehentai-圖片查詢',id: 'menuDemo3',contexts: ['image'],onclick: queryimg});
 5 
 6 function queryimg(info, tab) {
 7     var src = info.srcUrl; //獲取圖片對象的src
 8     fetch(src).then(function(response) {
 9     if(!response.ok) {
10         alert("圖片請求錯誤");
11         return;
12         }
13     var headers = response.headers;
14     var ct = headers.get('Content-Type');
15     var contentType = 'image/png';
16     if(ct !== null){
17       contentType = ct.split(';')[0];
18     }
19     
20     var blob = response.blob().then(function(blob) {
21     var formData = new FormData();
22     formData.append('sfile', blob);
23     formData.append('f_sfile', "search");
24     formData.append('fs_similar', "on");
25     $.ajax({
26         cache: false,
27         type: "POST",
28         processData: false, //必須為false
29         contentType: false, //必須為false
30         url: "https://exhentai.org/upload/image_lookup.php",
31         data: formData,
32         dataType: "multipart/form-data",
33         success: function(data, textStatus){
34               console.log(data); //請求成功並不會進入success,而是進入error,希望有懂的老哥在評論解惑
35         },
36         error: function (request) {
37             var contentText = request.responseText;
38             var url = contentText.match(/var getrowurl = "(.+?)"/)[1];  //從返回數據中正則提取出搜索結果頁面的url
39             window.open(url, '_blank').location; //新窗口打開搜索結果頁面
40            }
41     });
42     });
43 
44   });
45 }

推而廣之,在圖床上傳等問題上,這套方法也是適用的。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM