Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Prevent a function to be overriden again

I have a script loaded from external source after loadPlayer is loaded that looks like

function loadElement() {
    new YT.Player('youtube', {})    
}

also I am using in my TS file

function loadPlayer() {
    new window.YT.Player('youtube id', { ...somesettings })
}

however, the function loadPlayer is being executed first, then loadElement is creating new YT Player object which I do not want to happen. Are there any ways I can prevent this from happening? I tried adding Object freeze in loadPlayer or playing with proxy but it doesn’t seem to work. Also I don’t have a possibility to remove the external script. I need to make some workaround.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

A couple of options for you:

  1. Override window.YT.Player so only you can use it.

  2. Prevent the other script from loading at all.

Override window.YT.Player so only you can use it

Assuming it’s not a non-configurable binding, you can override the YT.Player property from within loadPlayer:

let OriginalYTPlayer;
function loadPlayer() {
    new window.YT.Player('youtube id', { ...somesettings })
    OriginalYTPlayer = window.YT.Player;
    window.YT.Player = function() { };
}

That makes any calls to YT.Player do nothing. If you need to use it, you can use OriginalYTPlayer instead. Of course, this may mess up other things you’re relying on that you haven’t mentioned.

Prevent the other script from loading

Assuming that the other script is a script, not a module, and that it’s loaded after your script is loaded, you can blow it up and prevent it from loading by defining loadElement yourself using a let or const:

function loadPlayer() {
    // ...
}
const loadElement = null;

Then, when the other script is loaded, it blows up with an error and doesn’t execute at all:

<script>
const loadElement = null;
</script>
<script>
function loadElement() {
    new YT.Player('youtube', {})    
}
</script>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading