Chrome Extension遷移第三方影象至Shopify填坑記

某日有需求,將第三方的圖片遷移到Shopify平臺上,功能全部由一個Chrome擴充套件實現,不依賴三方伺服器,現記錄開發過程中填坑過程:

坑一•跨域

最新的Chrome中已不允許擴充套件的content_script中進行跨域

,即便是已經在manifest檔案中明確宣告也是不可以的。

Regular web pages can use the XMLHttpRequest object to send and receive data from remote servers, but they‘re limited by the same origin policy。 Content scripts initiate requests on behalf of the web origin that the content script has been injected into and therefore content scripts are also subject to the same origin policy。 (Content scripts have been subject to CORB since Chrome 73 and CORS since Chrome 83。) Extension origins aren’t so limited - a script executing in an extension‘s background page or foreground tab can talk to remote servers outside of its origin, as long as the extension requests cross-origin permissions。

故此填這個坑只能走如下的流程:

content_script

中向

background page

傳送訊息,請求讀取三方圖片資料。

在background中讀取三方圖片資料後將圖片資料轉換成Base64字串。

再把Base64字串傳遞給content_script,完成一個讀取資料的流程

坑二•訊息中的非同步

不要將

chrome.runtime.onMessage.addListener

的回撥函式定義為async,否則訊息無法回傳,具體的原因是

chrome.runtime.sendMessage是單次連結的

,也就是說當

addListener回撥結束後,連結就已斷開了。具體細節請自行參考JavaScript的執行方式,或者記住這是一個坑就好。

故此填這個坑,有兩種方法:

強制同步的Ajax請求,進而可使用同步的訊息監控回撥。

使用chrome.runtime.connect建立長連線(推薦)

坑三•Shopify的影象上傳

說這是個坑也不盡然,只是Shopify請求上傳影象比較繁瑣罷了。

透過graphql/core?operation=stagedUploadsCreate介面獲取上傳引數。

透過前方獲取的引數+圖片檔案POST至shopify。s3。amazonaws。com,上傳檔案,並返回臨時檔案路徑。

向graphql/core?operation=FileCreate介面傳遞上面獲取的到臨時檔案路徑,實現檔案的建立。

沒坑呀?坑在哪?誰告訴你沒坑的,

第三部不返回最終檔案路徑是不是坑?

故此填這個坑,就需要一個取巧的辦法:

就是第2部返回的路徑與第3部生成的路徑是有規律相關的,自行轉換一下。

另外一種方法就是,再請求一遍檔案列表(不推薦)。

此坑填得不好,因為不知道這個規律是否問題,目前暫無問題。