我想通过设置滚动深度的自定义事件来跟踪用户行为。我真的很喜欢comradsocks.com的设置,在这里,我尝试使用facebook文档将它们作为滚动长度的模型。 https://developers.facebook.com/docs/facebook-pixel/advanced/
这是我遇到的错误。
Uncaught TypeError: Cannot read property 'scrollHeight' of null
at getDocumentLength ((index):60)
at getScrollableLength ((index):72)
at executeWhenReachedPagePercentage ((index):79)
at (index):117
这是我正在使用的代码。
var executeWhenReachedPagePercentage = function(percentage, callback) {
if (typeof percentage !== 'number') {
console.error(
'First parameter must be a number, got',
typeof percentage,
'instead',
);
}
if (typeof callback !== 'function') {
console.error(
'Second parameter must be a function, got',
typeof callback,
'instead',
);
}
function getDocumentLength() {
var D = document;
return Math.max(
D.body.scrollHeight, D.documentElement.scrollHeight,
D.body.offsetHeight, D.documentElement.offsetHeight,
D.body.clientHeight, D.documentElement.clientHeight
)
}
function getWindowLength() {
return window.innerHeight ||
(document.documentElement || document.body).clientHeight;
}
function getScrollableLength() {
if (getDocumentLength() > getWindowLength()) {
return getDocumentLength() - getWindowLength();
} else {
return 0;
}
}
var scrollableLength = getScrollableLength();
window.addEventListener("resize", function(){
scrollableLength = getScrollableLength();
}, false)
function getCurrentScrolledLengthPosition() {
return window.pageYOffset ||
(document.documentElement || document.body.parentNode || document.body).scrollTop;
}
function getPercentageScrolled() {
if (scrollableLength == 0) {
return 100;
} else {
return getCurrentScrolledLengthPosition() / scrollableLength * 100;
}
}
var executeCallback = (function() {
var wasExecuted = false;
return function() {
if (!wasExecuted && getPercentageScrolled() > percentage) {
wasExecuted = true;
callback();
}
};
})();
if (getDocumentLength() == 0 ||
(getWindowLength()/getDocumentLength() * 100 >= percentage)) {
callback();
} else {
window.addEventListener('scroll', executeCallback, false);
}
};
//scroll 50%
executeWhenReachedPagePercentage(50, function() {
fbq('track', 'SL-ScrollDepth-55');
});
//scroll 75%
executeWhenReachedPagePercentage(75, function() {
fbq('track', 'SL-ScrollDepth-75');
});
//scroll 100%
executeWhenReachedPagePercentage(95, function() {
fbq('track', 'SL-ScrollDepth-95');
});
///
</script>
<!-- End Facebook -->
当我滚动时,像素应该触发事件,但是我只是遇到了这个错误。