브라우저의 요소들과 자바스크립트 엔진 , 변수를 담고 있는 객체
대표적으로 객체는 screen, location, history, document 있고 메소드는 parseInt, isNaN이 있다.
window.close()
현재 창을 닫는다.
window.open()
새 창을 연다. 팝업창으로 열 수도 있고 새 탭으로 열 수도 있다. window.open('주소','새 탭 옵션','각종 옵션')
ex_ 1. window.open('https://velog.io/@hkbvc1222') => 새 탭으로 열기 2. window.open('https://velog.io/@hkbvc1222', '_self') => 새 탭으로 열기 3. window.open('', '','width=300, height=300') => 팝업창 열기
새로 열린 창을 변수로 저장할 수도 있다.
ex_ 브라우저 열고 console창에 입력해보기. 1. const popup = window.open('','','width= 400, height = 200') popup.document.write('Hellow')
2. const css = 'position:fixed; top:0; left:0; width: 100px; height:100px; border:2px #990F36 solid; background: #2EE644; cursor: pointer; z-index:1000;' const popup = window.open('','','width= 400, height = 200'); const button = window.document.createElement('button'); button.setAttribute('style',css); button.innerText='popup.close()' button.onclick=()=> popup.close(); popup.document.body.appendChild(button);
window는 전역객체 (global object => global scope에 항상 존재하는 객체)이므로 생략가능하다. ex_ open('https://velog.io/@hkbvc1222')
window.encodeURI() , window.decodeURI()
만약 주소에 한글이 들어갈 경우, Javascript에서는 '%EB%82%98%EB%A7%8C%EC%9D%98%20%EB%A9%94%EB%AA%A8'와 같은 이상한 글자로 변환된다. 한글을 암호화하고 싶다면 encodeURI('한글') , 암호화된 한글을 한글로 변환하고 싶다면 decodeURI('암호화된 한글')
ex_ 브라우저 개발자도구 console 창에 입력해보기. 1. const logCss = 'padding:20px; background: #2EE644; color: #990F36;fontWeight: bold;' const encodeMemo = encodeURI('나만의 메모') const decodeMemo = decodeURI(encodeMemo) console.groupCollapsed('%c click me',logCss) console.log('encodeMemo:',encodeMemo) console.log('decodeMemo:',decodeMemo) console.groupEnd()
window.setTimeout(함수, 밀리초) , window.setInterval(함수, 밀리초)
setTimeout => 지정한 밀리초 뒤에 실행 => clearTimeout setInterval => 지정한 밀리초마다 실행 => clearInterval
ex_ 브라우저 개발자도구 console 창에 입력해보기. 1. const setTime = setTimeout(()=>{console.log('timeout')},1000) clearTimeout(setTime) // => 1초뒤에 log가 안찍힌다.
1-1. const setTime = setTimeout(()=>{console.log('timeout')},1000) // => 1초뒤에 log가 찍힌다.
2-1. let count = 0 const logCss = 'padding:20px; background: #2EE644; color: #990F36;fontWeight: bold;' const interval = setInterval(()=>{ count+=1; console.log(`%c ${count} second`, logCss); }, 1000 ); setTimeout(()=>{clearInterval(interval)},2000) // => 1초마다 log가 찍히고 2초 뒤엔 안찍힌다. result => 'interval 2' 이후에 안찍힘.
window.getComputedStyle(태그)
태그의 style을 찾을 수 있는 method. => 현재 적용된 css 속성 값을 알 수 있다.
ex_ 브라우저 console창에 입력해보세요. 1. const css = 'position: fixed; top:0; left:0; width: 200px; height:200px; border:2px #990F36 solid; background: #2EE644; z-index: 1000;' const div = document.createElement('div') div.id = 'divId' div.setAttribute('style',css) document.body.appendChild(div) console.log(getComputedStyle(document.getElementById('divId'))); //**언제 응용할 수 있을지 잘 모르겠다..
DOM, BOM
전역 객체중, document는 Dom(Document Object Model)이라고 부르고, 나머지 브라우저에 대한 정보를 BOM(Browser Object Model) 이라 부른다.
navigator
브라우저나 운영체제(OS)에 대한 정보 (navigator.userAgent)를 바탕으로 유저의 정보를 분석할 수 있다. 한 예시로 HTML5기반 canvas 게임을 만들 때, Android => 동영상 자동재생 가능. 소리도 가능 IOS => 동영상은 유저의 제스처(유저가 동영상을 인식한 제스처(클릭, 터치)가 있어야 재생/소리 가능, 음소거로는 자동 재생가능 ) 의 차이가 있어 유저의 기기마다 분기를 쳐줘야 하는 작업이 필요했다.
이외의 GPS나 배터리를 체크하는 기능도 개발중이라 들어 눈여겨 봐야할 것 같다.
ex_ 브라우저 console 창에 입력해보세요. navigator.userAgent; // 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/101.0.4951.67 Safari/537.36' // window 10 64bit, chrome101버전 사용중.
screen
화면에 대한 정보를 알려준다. 유저의 브라우저/ 기기의 크기가 변할때(모바일 가로/세로 회전), canvas의 비율을 맞춰주는 방식으로 사용했었다. 1280/720 비율
const app = document.getElementById('app') const fullWidthRatio = innerWidth / 1280; const fullHeightRatio = innerHeight / 720; const isFullWidth = 720 * fullWidthRatio < innerHeight const scale = isFullWidth ? fullWidthRatio : fullHeightRatio; app.setAttribute('style',`width:${innerWidth}px; height:${innerHeight}px; transform: translate(-50%,-50%) scale(${scale}); `)
location
location 객체는 주소에 대한 정보를 알려준다. (protocol, host, hostname, pathname, href, port, search, hash 속성을 이용)
ex_ location.host; // 'velog.io' location.hostname; // 'velog.io' location.protocol; // 'https:' location.href; // 'https://velog.io/@hkbvc1222' location.pathname; // '/@hkbvc1222'
앞으로 이동 => history.forward() or history.go(1)
뒤로 이동 => history.back() or history.go(-1)
history.go(페이지 수)
history.length => 뒤로가기 할 수 있는 페이지의 개수
페이지를 이동하지 않고 단순히 주소만 변경.
history.pushState(객체, 제목, 주소)
history.replaceState(객체, 제목, 주소)
ex_
location.host; // 'velog.io'
location.hostname; // 'velog.io'
location.protocol; // 'https:'
location.href; // 'https://velog.io/@hkbvc1222'
location.pathname; // '/@hkbvc1222'
예제
다음 코드는 주어진 상태, 제목, URL을 사용해 새로운 세션 기록을 생성합니다.const state = { 'page_id': 1, 'user_id': 5 } const title = '' const url = 'hello-world.html'
history.pushState(state, title, url)