Created
September 16, 2016 11:59
-
-
Save villelahdenvuo/b35768ba4daec99843e0c5cbab1885c5 to your computer and use it in GitHub Desktop.
BrowserSync restore scroll position
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* eslint-disable */ | |
// Inspired by https://github.com/BrowserSync/browser-sync/issues/273#issuecomment-57427711 | |
(function ($window, $document, bs) { | |
var socket = bs.socket; | |
var selector = '[md-scroll-y]'; | |
var PRE = "<<BS_START>>"; | |
var SUF = "<<BS_END>>"; | |
var regex = new RegExp(PRE + "(.+?)" + SUF); | |
var saved = {}; | |
// Listen for the event in other browsers | |
socket.on('browser:reload', function (scrollTop) { | |
var $elem = $document.querySelector(selector); | |
if (!$elem) return; | |
var newname = [PRE, JSON.stringify({ | |
bs: { scroll: { x: 0, y: $elem.scrollTop } } | |
}), SUF].join(""); | |
$window.name = newname; | |
}); | |
try { | |
var json = $window.name.match(regex); | |
if (json) { | |
saved = JSON.parse(json[1]); | |
} | |
} catch (e) { | |
saved = {}; | |
} | |
/** | |
* If the JSON was parsed correctly, try to | |
* find a scroll property and restore it. | |
*/ | |
if (saved.bs && saved.bs.scroll) { | |
var func = setInterval(function () { | |
var $elem = $document.querySelector(selector); | |
if (!$elem) return; | |
$elem.scrollTop = saved.bs.scroll.y; | |
clearInterval(func); | |
}, 200); | |
} | |
/** | |
* Remove any existing BS json from window.name. | |
*/ | |
$window.name = $window.name.replace(regex, ""); | |
})(window, document, ___browserSync___); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment