Clipboard API
가끔 사진 복사 붙여넣기를 해야할떄
전의 사진이 다시 필요할때가 있는 경우가 있다.
구글 확장 프로그램에서는 다들 클립보드 텍스트 히스토리 추적만 지원해서
이미지 클립보드 히스토리 확장 프로그램을 구현하면 좋을 것 같다는 생각을 해서 이것이 가능한지 찾아보았고, 오늘 배운 내용들을 정리해보려한다.
클립보드에 관한 함수는 크게 document.execcommand('copy/cut/paste'와 Clipboard API로 나뉜다.
현재 document.execCommand함수는 공식적으로 deprecated되었지만 아직까지 몇몇 동작들은 작동되는 양상이고,
Clipboard API는 이를 대체하기 위해 나온 API로 최근에 나온 API라 몇몇 브라우저에서는 지원이 안되거나 호환이 애매한 경우가 있다고 한다. (그러나 우리는 크롬 확장 프로그램을 만들거고 크롬76 이후에서는 잘 지원한다.)
navigator.clipboard.readText().then(
clipText => document.querySelector(".editor").innerText += clipText);
Clipboard API에서는 별도의 객체를 선언하지 않고 navigator.clipboard를 사용해 접근한다.
메서드로는 read, readText, write, writeText를 가지고 있는데, readText, writeText같은 경우 텍스트를, read,write같은 경우에는 이미지 등의 데이터를 다룰수 있다.
모든 메서드들은 비동기적으로 실행되므로 Promise를 반환한다.
또한 실행하려면 권한이 필요한데, 브라우저 활성 탭에서는 clipboard write이 바로 허용되지만, clipboard read 같은 경우는 별도로 사용자가 권한을 부여해주어야한다.
Clipboard API같은 경우 HTTPS 상에서만 허용되며 파이어폭스 같은 경우 clipboard-read, clipboard-write 권한이 지원이 안되므로 사용할 수 없다.
만약 Clipboard API를 사용해서 확장 프로그램을 만든다면 매 사이트마다 권한을 허용해주어야 한다.
그러나 검색하면서 찾은 결정적 문제가 있는데 바로 이것이다!
10. Security Considerations
Enabling authors to change what is copied by a user, or to make an automated copy of something that was never selected and allowing unrestricted calls to paste information can raise various security concerns.
Some example scenarios include:
A user selects a link and copies it, but a different link is copied to the clipboard. The effect of this can range from an unexpected result on pasting to an attempted "phishing" attack.(Self-XSS) Shell commands or executable script can be placed in the clipboard with the intent that the user will run the pasted content.An image that is specially crafted to exploit bugs in the core OS image handling code can be written to the clipboard.
Copy Link address나 image등은 XSS 공격이나 코어 OS 이미지 처리 코드의 버그를 이용하기 위해 만든 특수 이미지가 클립보드에 들어갈수 있으므로 막아놨다는 것이다
괜히 사람들이 이미지 클립보드 저장 확장 프로그램을 구현하지 못한게 아니었다...
https://w3c.github.io/clipboard-apis/#security
Clipboard API and events
Abstract This document describes APIs for accessing data on the system clipboard. It provides operations for overriding the default clipboard actions (cut, copy and paste), and for directly accessing the clipboard contents. Status of this document This sec
w3c.github.io
Chrome Extension
크롬 익스텐션에서는 크게 3가지 스크립트로 이루어져있다.
Content: 현재 사용자가 사용하는 브라우저창의 DOM 등에 접근하거나 제어하는 스크립트
Background: 익스텐션이 실제로 동작하는 스크립트
Popup: extension을 누르면 뜨는 작은 창, 혹은 별도의 창에 관련된 스크립트
만약 내가 구현을 하려고 했다면 Content 스크립트에서 복사한 내용을 background에 담아와서 이를 가공해서 Popup에서 저장한 클립보드 내용을 보여주는 식으로 작성해야했다.
content, background, popup, 이들이 통신하려면
chrome.runtime.sendMessage({greeting: "hello"}, function(response) {
console.log(response.farewell);
});
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
console.log(sender.tab ?
"from a content script:" + sender.tab.url :
"from the extension");
if (request.greeting == "hello")
sendResponse({farewell: "goodbye"});
}
);
이렇게 sendMessage와 addListener를 통해서 가능하다. 이외에 탭이 활성화되었을때 탭을 추가할떄 등의 브라우저 액션 같은 경우도
chrome.tabs.onCreated.addListener(function callback)
이렇게 가능하다!
다양한 chrome API가 있으니 필요하면 API 레퍼런스를 찾아보자
https://developer.chrome.com/docs/extensions/reference/
API Reference - Chrome Developers
The complete reference to all APIs made available to Chrome Extensions. This includes APIs for the deprecated Chrome Apps platform as well as APIs still in beta and dev.
developer.chrome.com
최근에 코테 준비만 몇일간 하다보니 오랜만에 적는 TIL인데... 이런거 하니 또 재밌다.
내일은 KMP 알고리즘 공부해야지
'TIL' 카테고리의 다른 글
TIL 2022-02-07 JS 이벤트 전달, 폰트 관련 (0) | 2022.02.07 |
---|---|
TIL 2022-02-03 JS ErrorHandling, svgr, babel-loader vs ts-loader (0) | 2022.02.03 |
TIL 2022-01-25 Topdown slider, css text animation (0) | 2022.01.25 |
TIL 2022-01-20 HashTable, 정렬 구현하기 (0) | 2022.01.20 |
TIL 2022-01-19 JS 중복된 값 제거, useLayoutEffect, useImperativeHandle, 힙소트 관련 (0) | 2022.01.19 |