JS Access Method from outside of script file

This one might be a silly question but I really need to fix a tiny slider issue for it’s autoplay.

The problem is, are there any way of accessing already instanced object from outside of the script file itself? Note: without knowing the variable / const name of it too.

Example: Someone from previous Dev team made a gallery of TNS / Tiny Slider like below:

var someName = tns({
  container: '.carousel',
  items: 3,
  autoplay: true,
});

basically it just creating a tns instance from that container. In browser, it shows something like this

<div class="carousel tns-slider">
  <div class="tns-item">...</div>
  <div class="tns-item">...</div>
  ...
</div>

The problem is, the code for building that someName tns is from external url that I don’t know where is it. Also, I don’t know what actually the “someName” variable’s name are, so it’s already declared there instanced and working properly, I just need to disable the autoplay.

I’ve tried from documentation from https://github.com/ganlanyuan/tiny-slider

However, it always show how to destroy() or stop() or play() if I know the name of the instanced var (the “someName”) while currently I don’t have any access to the file nor knowing the path, I just asked to update via new JS file called updates-scripts.js. This is also demonstrated on codepen and other tutorials.

Are there any way of me to access method of it via let say jQuery(‘.carousel’) or documentQuerySelector?

Thank you

Answer

This can be done by monkeypatching TNS. Add a setter for window.tns before the library loads. Once the library loads and assigns to the window, invoking the setter, you can assign something else to the window that intercepts the window.tns call that the external script (that you don’t have any control over) uses.

Then simply access the .container property of the object passed in, and do whatever you need to do with it:

// Example code from the external script you have no control over
var slider = tns({
  container: '.my-slider',
  items: 3,
  slideBy: 'page',
  autoplay: true
});
<script>
// Insert your monkeypatching script here, before anything else
Object.defineProperty(window, 'tns', {
  set(tns) {
    // Delete this setter
    delete window.tns;
    window.tns = function(...args) {
      const container = args[0]?.container;
      console.log('container:', container);
      return tns.apply(this, args);
    };
  },
  configurable: true
});
    
</script>


<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/tiny-slider.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/tiny-slider/2.9.3/tiny-slider.css">
<div class="my-slider">
  <div>foo</div>
  <div>bar</div>
  <div>baz</div>
</div>