Home > Enterprise >  Prevent a function to be overriden again
Prevent a function to be overriden again

Time:11-18

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.

CodePudding user response:

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>

  • Related