# 複製與貼上圖片功能
###### tags: `Javascript`
## 使用者情境
設置一個按鈕,讓使用者按下後可以複製圖片(非圖片網址),到 FB, Line 等後能直接貼上圖片。
## 使用技術
使用 [Clipboard API](https://developer.mozilla.org/en-US/docs/Web/API/Clipboard_API)
### 參考來源
* [Image support for the async clipboard API](https://web.dev/image-support-for-async-clipboard/#images)
* [Async Clipboard API: Accessing the clipboard using JavaScript](https://arnellebalane.com/blog/async-clipboard-api/)
> 補充資料
> [Blob](https://developer.mozilla.org/zh-TW/docs/Web/API/Blob)
> [JavaScript navigator Object](https://www.fooish.com/javascript/navigator.html)
> [Async Clipboard API來了](https://www.jishuwen.com/d/2CXA/zh-tw)
### 限制
1. 圖片必須為 png (?)
2. 貼上時需要使用者同意
## 遇到問題-1
### fetch error
> No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://xxxxxxxx' is therefore not allowed access. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
Adding mode: 'no-cors' won’t magically make things work. In fact it makes things worse, because one effect it has is to tell browsers, “Block my frontend JavaScript code from looking at contents of the response body and headers under all circumstances.” Of course that’s almost never what you want.
However, one thing that will work is if you send your request through a **CORS proxy**
資料來源:[Trying to use fetch and pass in mode: no-cors](https://stackoverflow.com/questions/43262121/trying-to-use-fetch-and-pass-in-mode-no-cors)
### 解決 CORS 問題
使用 **[cors-anywhere](https://cors-anywhere.herokuapp.com/)**
* [如何解決跨網域存取被拒絕問題](https://andy6804tw.github.io/2019/09/21/fix-cors-problem/#%E5%A6%82%E4%BD%95%E8%A7%A3%E6%B1%BA%E8%B7%A8%E7%B6%B2%E5%9F%9F%E5%AD%98%E5%8F%96%E8%A2%AB%E6%8B%92%E7%B5%95%E5%95%8F%E9%A1%8C)
* [使用跨域代理伺服器(CORS PROXY),解決讀取第三方網站資料問題﹍實作範例](https://www.wfublog.com/2018/11/js-cors-proxy.html#section3)
> 補充資料
> [輕鬆理解 Ajax 與跨來源請求](https://blog.techbridge.cc/2017/05/20/api-ajax-cors-and-jsonp/)
> [深入認識跨域請求](https://www.ithome.com.tw/voice/129558)
> [和 CORS 跟 cookie 打交道](https://medium.com/d-d-mag/%E5%92%8C-cors-%E8%B7%9F-cookie-%E6%89%93%E4%BA%A4%E9%81%93-dd420ccc7399)
## 遇到問題-2
### Android
[Google To Allow Copying Of Images From Chrome To Clipboard On Android](https://www.androidheadlines.com/2020/01/google-chrome-android-clipboard-copy-paste-feature-spotted.html)
Chrome 開發中
可以複製並貼在同一個網頁上,但無法貼在其他地方
註:chrome 在 Android 上目前對圖片長按時有的功能:在新分頁開啟、下載圖片、透過 google 搜尋這張圖片、分享圖片
### iOS
無法複製:Failed to find variable clipboardItems
註:safari & chrome 在 iPhone 上原本就有支援對圖片長按時有拷貝圖片的功能

### 討論
[How do I simply copy a google photo to Clipboard so I can do a simple paste into any app?](https://support.google.com/photos/thread/2514728?hl=en)
## 結論
電腦上實作可以,但現在在 Android 和 iPhone 上執行有困難