2

I'm writing a specific javascript plugin for a specific website.

In one of my methods i want to use window.scrollTo but unfortunately the site owner has overridden the native functionality of this function (also window.scroll).

So i'm thinking about 2 possible solutions:

  1. Write my own myScrollTo implementation
  2. Somehow detect if the native function is overridden and call the native function.

If you have any ideas on this, i will be very glad to hear them :)

Thanks.

dimshik
  • 1,251
  • 15
  • 17

3 Answers3

3

Well you can create an iframe and use its window instance to get the native implementation of scrollTo. The following code should work

var iframe = document.createElement('iframe');
iframe.style.display = 'none';
document.body.appendChild(iframe);
window.altScrollTo = iframe.contentWindow.scrollTo;

Now you should be able to use it as below

aScrollTo.call(window, 0, 600)
blessanm86
  • 31,439
  • 14
  • 68
  • 79
1

Well it's not the perfect solutions but is suites my current needs.

First i will check if the native function is overridden with this helpful piece of code :

function isFuncNative(f) {
       return !!f && (typeof f).toLowerCase() == 'function' 
       && (f === Function.prototype 
       || /^\s*function\s*(\b[a-z$_][a-z0-9$_]*\b)*\s*\((|([a-z$_][a-z0-9$_]*)(\s*,[a-z$_][a-z0-9$_]*)*)\)\s*{\s*\[native code\]\s*}\s*$/i.test(String(f)));
}

Source: https://stackoverflow.com/a/7536972/3009194

Then i will try the alternatives : window.scroll as the is no difference between window.scroll() and window.scrollTo()

And finally if this one is also overridden, i guess i will use document.body.scrollTop

Yes i know, there is a possibility that the body is not the scrolling Element. Unfortunately the document.scrollingElement is still a draft and not supported in most browsers.

So the final code will look something like this:

   function myScroll(left, top) {
       if (isFuncNative(window.scrollTo)) {
           window.scrollTo(left, top);
       } else if (isFuncNative(window.scroll)) {
           window.scroll(left, top);
       } else {
           document.body.scrollLeft = left;
           document.body.scrollTop = top;
       }
   }

   myScroll(0,150);
Community
  • 1
  • 1
dimshik
  • 1,251
  • 15
  • 17
0

You can use the scrollIntoView method.

const element = document.getElementById("content");
element.scrollIntoView();

https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView

Ali Bektash
  • 572
  • 5
  • 15