URL, URLSearchParams, DOMString

tapata·2022년 2월 24일
0

JavaScript - Web APIs

목록 보기
1/5

URL

  • used to parse, construct, normalize, and encode URLs
  • Blob, File, MediaSource를 입력받아 해당 object를 나타내는 주소(=DOMString)를 반환하는 createObjectURL()함수 제공
  • DOMString은 생성된 브라우저에서만 일시적으로 유효한 주소

properties & methods

// 현재 주소로 URL객체 생성 
// https://search.naver.com/search.naver
// ?where=nexearch&sm=top_hty&fbm=1&ie=utf8&query=doctor+strange
const url = new URL(location.href)

/* Properties */

// 'search.naver.com'
url.host 

// 'search.naver.com'
url.hostname 

// 'https://search.naver.com/search.naver?
// where=nexearch&sm=top_hty&fbm=1&ie=utf8&query=doctor+strange'
url.href 

// 'https://search.naver.com'
url.origin

// '/search.naver'
url.pathname 

// 'https'
url.protocol 

// '?where=nexearch&sm=top_hty&fbm=1&ie=utf8&query=doctor+strange'
url.search 

// URLSearchParams 
url.searchParams 

/* method */

// 'https://search.naver.com/search.naver?
// where=nexearch&sm=top_hty&fbm=1&ie=utf8&query=doctor+strange'
url.toString() 

// 'https://search.naver.com/search.naver?
// where=nexearch&sm=top_hty&fbm=1&ie=utf8&query=doctor+strange'
url.toJSON() 




/* create Blob URL*/
URL.createObjectURL(File) // DOMString 
URL.createObjectURL(Blob) // DOMString
URL.createObjectURL(MediaSource) // DOMString


/* revoke */ 
URL.revokeObjectURL(domString)

URLSearchParams

  • url.searchParams : URLSearchParams
  • URL 인스턴스의 searchParams 프로퍼티

properties & methods

// 생성
let obj = { search : 'weather'}
let params = new URLSearchParams(obj)

// method
params.has('search') // true
let search = params.get('search') //  search = 'weather'

params.append('cities','new york')
params.append('cities','london')
params.append('cities','toronto')

params.get('cities') // 'new york'
params.getAll('cities') // ['new york', 'london', 'toronto']

params.keys() // IterableIterator<string>
params.values() // IterableIterator<string>


params.toString() // 'search=weather&cities=new+york&cities=london&cities=toronto'
params.set('cities','boston')

params.delete('cities')

DOMString

  • a sequence of 16-bit unsigned integers
  • represent a object URL

e.g. 이미지 파일을 브라우저의 form 으로 받아서 띄우기

1. 이미지를 받는 form tag + 받은 이미지를 보여줄 div tag

<script defer src="./main.js"></script>
<form action="">
  <input type="file" accept="image/*">
</form>

<div class="img"></div>

2. 이미지가 업로드 되면 업로드된 파일에 대해 주소 생성

let input = document.querySelector('input');
input.addEventListener('change',(e)=>{
  console.log(e.target.files[0])
  

  // File로 부터 DOMString 생성, *현 브라우저 에서만 유효
  const src = URL.createObjectURL(e.target.files[0])
  console.log(src) // blob:http://127.0.0.1:5500/0f55f0ff-6ad2-4fea-ac92-6c621ab083e9
  
  // 이미지 태그 생성하고 src 설정
  const img = document.createElement('img');
  img.src = src; 
    
  document.querySelector('.img').appendChild(img);
})
profile
hello

0개의 댓글