Locksleyu
Locksleyu

Reputation: 5355

Removing a single specific user script from WKUserContentController

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.

Upvotes: 1

Views: 1211

Answers (2)

user3335999
user3335999

Reputation: 421

You can try something like this:

-(bool)removeUserScriptByValue:(nonnull NSString*)scriptValue{
    bool retVal = false;
    NSMutableArray<WKUserScript*>* userscripts = [NSMutableArray arrayWithArray:self.configuration.userContentController.userScripts];
    for(int i=0; i<userscripts.count; i++){
        WKUserScript* userScript = [userscripts objectAtIndex:i];
        if([userScript.source rangeOfString:scriptValue].location != NSNotFound){
            retVal = true;
            [userscripts removeObjectAtIndex:i];
            break;
        }
    }
    if(retVal){
        [self.configuration.userContentController removeAllUserScripts];
        for(WKUserScript* script in userscripts)
            [self.configuration.userContentController addUserScript:script];
    }
    return retVal;
}

Upvotes: 0

AirXyg&#232;ne
AirXyg&#232;ne

Reputation: 2919

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.

Upvotes: 1

Related Questions