WKWebView Does not Suspend JS When App is Backgrounded

Originator:jonahw.admob
Number:rdar://7739943 Date Originated:6/16/20
Status:Open Resolved:
Product:WebKit Product Version:13.5.1
Classification:Incorrect/Unexpected Behavior Reproducible:Yes
 
Starting on iOS 13.5.1, an app which contains a WKWebView may consume CPU usage even when backgrounded.

Example code:

- (void)viewDidLoad {
  [super viewDidLoad];
 
  _webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, 400, 400)];
  _webView.navigationDelegate = self;
  [self.view addSubview:_webView];
 
  [self doJS];  
}

- (void)doJS {
  [_webView evaluateJavaScript:@"setTimeout({console.log('text')}, 10000);" completionHandler:^(id _Nullable arg, NSError * _Nullable error) {
    NSLog(@"Ran some JS!");
  }];
 
  dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
    [self doJS];
  });
}

Steps to reproduce:
1. Create a blank app and add the provided code to the ViewController.
2. Launch the app and then background it.

Expected behavior:
The app ceases using the battery and CPU.

Observed behavior:
The webview continues executing JS, using up both the battery and CPU.

After around 30 seconds of backgrounding on iOS 13.5.1, the following errors show up:

[ProcessSuspension] Background task expired while holding WebKit ProcessAssertion (isMainThread? 1).
2020-06-16 17:00:07.314584-0700 FoundationExperiments[1685:89122] [ProcessSuspension] 0x2802523d0 - WKProcessAssertionBackgroundTaskManager: Ignored request to start a new background task because the application is already in the background
2020-06-16 17:00:07.317894-0700 FoundationExperiments[1685:89122] [ProcessSuspension] 0x2802523d0 - WKProcessAssertionBackgroundTaskManager: Ignored request to start a new background task because the application is already in the background

Testing the provided code on iOS 13.3.1, the JS runs while backgrounded for ~15 seconds before suspending.

Comments


Please note: Reports posted here will not necessarily be seen by Apple. All problems should be submitted at bugreport.apple.com before they are posted here. Please only post information for Radars that you have filed yourself, and please do not include Apple confidential information in your posts. Thank you!