prgrm
prgrm

Reputation: 3833

Preventing an external source to modify my HTML with Javascript

I have something like this:

$('mySelector').html("this is mine now");

Then some external JS I cannot edit or get rid of does, among other thing:

$('mySelector').on("focus", function(e){
    //lots of stuff
    $(this).empty();
})

Is there any way for the element to retain the HTML I added previously?

Upvotes: 2

Views: 468

Answers (2)

Tasos
Tasos

Reputation: 2036

This is NOT a pattern that should be used in my opinion, but based on this you can define a second handler for the same event. I'm not sure if you have to define it before or after the existing handler, but the result is that only the one handler will be triggered.

If it gets triggered it means that your handler is not listening on the same element as the other one. If that's the case you could attach a new listener to a child dom element of your this and use event.preventDefault() && event.stopPropagation() inside it so that the outer handler does not run

Upvotes: 1

Petr Hejda
Petr Hejda

Reputation: 43491

You can use the Content-Security-Policy directives to prevent browsers from loading JS from external domains.

Content-Security-Policy: script-src 'self' https://example.com;

This will allow executing JS only from your own domain and from example.com.


So basically, you can limit access on the domain level. Note that an <iframe> can load a different domain which can have different access rules.

But apart from this, there is currently no way to specify what DOM elements on your page a JS script can or cannot access/modify.

Upvotes: 1

Related Questions