Skip to content

Instantly share code, notes, and snippets.

@dlxotn216
Last active May 4, 2018 15:32
Show Gist options
  • Save dlxotn216/e233adfb8b8ca43f3ac2405401d9ef39 to your computer and use it in GitHub Desktop.
Save dlxotn216/e233adfb8b8ca43f3ac2405401d9ef39 to your computer and use it in GitHub Desktop.
jQuery 브라우저 뒤로가기 예제 코드

$(document).ready(function($) {
	initPage();
});

/**
 * Page init script
 */
function initPage(){
	if (window.history && window.history.pushState) {
		pushHistory({ action: 'forward' }, null, '../#'); 

		$(window).on('popstate', function() {
			alert('뒤로가기 버튼 클릭 됨');        
		});
	}
}

/**
 * 브라우저의 History 객체에 State를 push 한다
 * 
 * @param data Push 한 State를 Load 할 때 함께 Load 될 데이터 Object
 * @param title State의 title
 * @param url State의 URL
 */
function pushHistory(data, title, url){
	if(isHtml5Supported()){
		window.history.pushState(data, title, url);  //Html 5 API를 통해 history 추가	
	} else {
		//polyfill code 
	}
}

/**
 * 현재 브라우저가 HTML5 API를 지원하는지 여부를 반환한다
 * 
 * Modernizr룰 third party로 사용하고 있다면 대체 가능하다
 * {@link https://modernizr.com/}.
 * 
 * @returns {boolean}
 */
function isHtml5Supported(){
	var test_canvas = document.createElement("canvas"); 
	return (test_canvas.getContext) ? true : false
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment