0

I'm using addUserScript() to add a user script to my WKWebView's WKUserContentController. I noticed that even if call loadRequest() the script stays around.

For certain use cases I may need to remove certain scripts and add others. However, it seems that the only way to remove scripts is removeAllUserScripts(). This is very inconvenient since it means I would have to remove all scripts and then re-add back the ones which I wanted to keep.

If anyone knows of any way to delete a specific script (by name, handle, etc.) please let me know.

Locksleyu
  • 4,822
  • 6
  • 46
  • 68

1 Answers1

1

I don't think "removing a script" is something possible (or even meaningful if I understand correctly your question).

A "script" is just text that is used to provide the Javascript environment with definitions of elements such as variables, functions, etc... Two scripts could very well over-ride each other (e.g. define the same function foo()), so depending on the order you loaded them, you have a different end environment (you only have the foo() definition of the last loaded script). So what would "remove a script" mean in that case ?

If you really want to get rid of elements of your Javascript environment, you can always re-define them to something that does not do anything (e.g. redefine foo() to {}). But I guess the simplest way is just not to use foo() any more.

AirXygène
  • 1,909
  • 11
  • 28
  • It is possible. Apple already provides a function to remove all user scripts: removeAllUserScripts. I am trying to do this for a single script so I don't interfere with other scripts that might have been added. – Locksleyu May 11 '20 at 20:54