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

# init(source:injectionTime:forMainFrameOnly:)

Creates a user script object that contains the specified source code and attributes.

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

## 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.

## Return Value

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

## Discussion

This method sets the script’s content world to the object in the [`page`](/documentation/WebKit/WKContentWorld/page) property of [`WKContentWorld`](/documentation/WebKit/WKContentWorld).

---

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)