<!--
{
  "availability" : [
    "iOS: 14.0.0 -",
    "iPadOS: 14.0.0 -",
    "macCatalyst: 14.0.0 -",
    "macOS: 11.0.0 -",
    "visionOS: 1.0.0 -"
  ],
  "documentType" : "symbol",
  "framework" : "WebKit",
  "identifier" : "/documentation/WebKit/WKUserScript/init(source:injectionTime:forMainFrameOnly:in:)",
  "metadataVersion" : "0.1.0",
  "role" : "Initializer",
  "symbol" : {
    "kind" : "Initializer",
    "modules" : [
      "WebKit"
    ],
    "preciseIdentifier" : "c:objc(cs)WKUserScript(im)initWithSource:injectionTime:forMainFrameOnly:inContentWorld:"
  },
  "title" : "init(source:injectionTime:forMainFrameOnly:in:)"
}
-->

# init(source:injectionTime:forMainFrameOnly:in:)

Creates a user script object that is scoped to a particular content world.

```
init(source: String, injectionTime: WKUserScriptInjectionTime, forMainFrameOnly: Bool, in contentWorld: WKContentWorld)
```

## Parameters

`source`

The script’s source code.

`injectionTime`

The time at which to inject the script into the webpage. For a list of possible values, see [`WKUserScriptInjectionTime`](/documentation/WebKit/WKUserScriptInjectionTime).

`forMainFrameOnly`

A Boolean value that indicates whether to inject the script into the main frame. Specify <doc://com.apple.documentation/documentation/Swift/true> to inject the script only into the main frame, or <doc://com.apple.documentation/documentation/Swift/false> to inject it into all frames.

`contentWorld`

The namespace in which to evaluate the script. This parameter doesn’t apply to changes your script makes to the underlying web content, such as the document’s DOM structure. Those changes remain visible to all scripts, regardless of which content world you specify. For more information about content worlds, see [`WKContentWorld`](/documentation/WebKit/WKContentWorld).

## Return Value

An initialized user script, or `nil` if initialization failed.

## Discussion

---

Copyright &copy; 2026 Apple Inc. All rights reserved. | [Terms of Use](https://www.apple.com/legal/internet-services/terms/site.html) | [Privacy Policy](https://www.apple.com/privacy/privacy-policy)