2

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?

2
  • What is this external JS? Is it an npm package? Commented Jun 15, 2021 at 11:39
  • @Tasos Bu it is from a Symfony bundle installed with composer. However, editing it or even overloading it is not desirable. Commented Jun 15, 2021 at 11:55

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

Comments

1

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.

2 Comments

Thanks. While this works, I am not trying to prevent all of it to work. Just conserve the HTML that the empty deletes.
Got it. But that's not possible with the current implementation of JS in browsers (see the last paragraph of my answer).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.