| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348 |
- //
- // IndeedJobBrowserWindowController.swift
- // App for Indeed
- //
- import Cocoa
- import WebKit
- /// Indeed job listing and apply flow in a `WKWebView`, embedded in the dashboard main panel or hosted in a window.
- final class IndeedJobBrowserViewController: NSViewController, WKNavigationDelegate, WKUIDelegate {
- /// When set, a leading **Home** control calls this so the host can hide the embedded browser (same-window UX).
- var onDismissEmbedded: (() -> Void)?
- private let webView: WKWebView = {
- let configuration = WKWebViewConfiguration()
- configuration.preferences.javaScriptCanOpenWindowsAutomatically = true
- return WKWebView(frame: .zero, configuration: configuration)
- }()
- private var pendingURL: URL?
- private let backButton = NSButton()
- private let forwardButton = NSButton()
- private let reloadButton = NSButton()
- private let dismissEmbeddedButton = NSButton(title: "Home", target: nil, action: nil)
- private let toolbarContainer = NSView()
- private var appearanceObserver: NSObjectProtocol?
- override func loadView() {
- view = NSView(frame: NSRect(x: 0, y: 0, width: 920, height: 720))
- }
- override func viewDidLoad() {
- super.viewDidLoad()
- webView.translatesAutoresizingMaskIntoConstraints = false
- webView.navigationDelegate = self
- webView.uiDelegate = self
- webView.customUserAgent = Self.desktopSafariLikeUserAgent
- configureToolbarButton(backButton, symbolName: "chevron.backward", action: #selector(goBack))
- configureToolbarButton(forwardButton, symbolName: "chevron.forward", action: #selector(goForward))
- configureToolbarButton(reloadButton, symbolName: "arrow.clockwise", action: #selector(reload))
- dismissEmbeddedButton.translatesAutoresizingMaskIntoConstraints = false
- dismissEmbeddedButton.bezelStyle = .rounded
- dismissEmbeddedButton.isBordered = true
- dismissEmbeddedButton.target = self
- dismissEmbeddedButton.action = #selector(dismissEmbedded)
- dismissEmbeddedButton.toolTip = "Return to the previous screen"
- toolbarContainer.translatesAutoresizingMaskIntoConstraints = false
- toolbarContainer.wantsLayer = true
- let barStack: NSStackView
- if onDismissEmbedded != nil {
- barStack = NSStackView(views: [dismissEmbeddedButton, backButton, forwardButton, reloadButton, NSView()])
- } else {
- barStack = NSStackView(views: [backButton, forwardButton, reloadButton, NSView()])
- }
- barStack.orientation = .horizontal
- barStack.spacing = 8
- barStack.alignment = .centerY
- barStack.distribution = .fill
- barStack.translatesAutoresizingMaskIntoConstraints = false
- toolbarContainer.addSubview(barStack)
- view.addSubview(toolbarContainer)
- view.addSubview(webView)
- var layoutConstraints: [NSLayoutConstraint] = [
- toolbarContainer.leadingAnchor.constraint(equalTo: view.leadingAnchor),
- toolbarContainer.trailingAnchor.constraint(equalTo: view.trailingAnchor),
- toolbarContainer.topAnchor.constraint(equalTo: view.topAnchor),
- toolbarContainer.heightAnchor.constraint(equalToConstant: 48),
- barStack.leadingAnchor.constraint(equalTo: toolbarContainer.leadingAnchor, constant: 12),
- barStack.trailingAnchor.constraint(equalTo: toolbarContainer.trailingAnchor, constant: -12),
- barStack.centerYAnchor.constraint(equalTo: toolbarContainer.centerYAnchor),
- backButton.widthAnchor.constraint(equalToConstant: 32),
- backButton.heightAnchor.constraint(equalToConstant: 28),
- forwardButton.widthAnchor.constraint(equalToConstant: 32),
- forwardButton.heightAnchor.constraint(equalToConstant: 28),
- reloadButton.widthAnchor.constraint(equalToConstant: 32),
- reloadButton.heightAnchor.constraint(equalToConstant: 28),
- webView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
- webView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
- webView.topAnchor.constraint(equalTo: toolbarContainer.bottomAnchor),
- webView.bottomAnchor.constraint(equalTo: view.bottomAnchor)
- ]
- if onDismissEmbedded != nil {
- layoutConstraints.append(dismissEmbeddedButton.heightAnchor.constraint(equalToConstant: 28))
- }
- NSLayoutConstraint.activate(layoutConstraints)
- updateNavigationButtons()
- applyCurrentAppearance()
- appearanceObserver = NotificationCenter.default.addObserver(
- forName: AppAppearanceManager.didChangeNotification,
- object: nil,
- queue: .main
- ) { [weak self] _ in
- self?.applyCurrentAppearance()
- }
- if let pendingURL {
- webView.load(URLRequest(url: pendingURL))
- self.pendingURL = nil
- }
- }
- deinit {
- if let appearanceObserver {
- NotificationCenter.default.removeObserver(appearanceObserver)
- }
- }
- func loadPage(_ url: URL) {
- if isViewLoaded {
- webView.load(URLRequest(url: url))
- } else {
- pendingURL = url
- }
- updateNavigationButtons()
- }
- /// Adds this controller as a child of `parent` and pins `view` to `host` (used by the dashboard main panel).
- func embed(in host: NSView, parent: NSViewController) {
- parent.addChild(self)
- view.translatesAutoresizingMaskIntoConstraints = false
- host.addSubview(view)
- NSLayoutConstraint.activate([
- view.leadingAnchor.constraint(equalTo: host.leadingAnchor),
- view.trailingAnchor.constraint(equalTo: host.trailingAnchor),
- view.topAnchor.constraint(equalTo: host.topAnchor),
- view.bottomAnchor.constraint(equalTo: host.bottomAnchor)
- ])
- }
- private func configureToolbarButton(_ button: NSButton, symbolName: String, action: Selector) {
- button.translatesAutoresizingMaskIntoConstraints = false
- button.bezelStyle = .texturedRounded
- button.isBordered = true
- button.image = NSImage(systemSymbolName: symbolName, accessibilityDescription: nil)
- button.imagePosition = .imageOnly
- button.target = self
- button.action = action
- }
- private func applyCurrentAppearance() {
- toolbarContainer.layer?.backgroundColor = AppDashboardTheme.chromeBackground.cgColor
- let accent = AppDashboardTheme.brandBlue
- dismissEmbeddedButton.contentTintColor = accent
- backButton.contentTintColor = accent
- forwardButton.contentTintColor = accent
- reloadButton.contentTintColor = accent
- }
- private func updateNavigationButtons() {
- backButton.isEnabled = webView.canGoBack
- forwardButton.isEnabled = webView.canGoForward
- }
- @objc private func goBack() {
- webView.goBack()
- }
- @objc private func goForward() {
- webView.goForward()
- }
- @objc private func reload() {
- webView.reload()
- }
- @objc private func dismissEmbedded() {
- onDismissEmbedded?()
- }
- func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
- updateNavigationButtons()
- }
- func webView(_ webView: WKWebView, didCommit navigation: WKNavigation!) {
- updateNavigationButtons()
- }
- func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
- guard IndeedWebBrowsingPolicy.allows(navigationAction: navigationAction) else {
- decisionHandler(.cancel)
- return
- }
- let isMainFrame = navigationAction.targetFrame?.isMainFrame ?? true
- if isMainFrame,
- let url = navigationAction.request.url,
- IndeedWebBrowsingPolicy.shouldForceGoogleAccountPicker(for: url) {
- let pickerURL = IndeedWebBrowsingPolicy.urlForcingGoogleAccountPicker(url)
- if pickerURL != url {
- webView.load(URLRequest(url: pickerURL))
- decisionHandler(.cancel)
- return
- }
- }
- decisionHandler(.allow)
- }
- /// Target=_blank / `window.open` without a frame: load in this view so apply flows stay in-app.
- func webView(_ webView: WKWebView, createWebViewWith configuration: WKWebViewConfiguration, for navigationAction: WKNavigationAction, windowFeatures: WKWindowFeatures) -> WKWebView? {
- guard navigationAction.targetFrame == nil,
- IndeedWebBrowsingPolicy.allows(navigationAction: navigationAction) else {
- return nil
- }
- var request = navigationAction.request
- if let url = request.url,
- IndeedWebBrowsingPolicy.shouldForceGoogleAccountPicker(for: url) {
- request = URLRequest(url: IndeedWebBrowsingPolicy.urlForcingGoogleAccountPicker(url))
- }
- webView.load(request)
- return nil
- }
- /// Desktop Safari UA helps Indeed serve a full desktop apply experience.
- private static let desktopSafariLikeUserAgent = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.4 Safari/605.1.15"
- }
- // MARK: - Google sign-in only (no Gmail, Help hub, Search, etc.)
- /// Limits embedded browsing on Google-owned hosts to OAuth / sign-in, while leaving Indeed and third-party apply sites unrestricted.
- enum IndeedWebBrowsingPolicy {
- static func allows(navigationAction: WKNavigationAction) -> Bool {
- guard let url = navigationAction.request.url else { return true }
- let isMainFrame = navigationAction.targetFrame?.isMainFrame ?? true
- if isMainFrame {
- return allowsMainFrameNavigation(to: url)
- }
- return allowsSubframeNavigation(to: url)
- }
- static func allowsMainFrameNavigation(to url: URL) -> Bool {
- guard let scheme = url.scheme?.lowercased() else { return false }
- if scheme == "about" || scheme == "blob" || scheme == "data" { return true }
- guard scheme == "http" || scheme == "https" else { return false }
- guard let host = url.host?.lowercased() else { return false }
- if !isGooglePropertyHost(host) {
- return true
- }
- return isAllowedGoogleSignInHost(host, path: url.path)
- }
- static func allowsSubframeNavigation(to url: URL) -> Bool {
- guard let scheme = url.scheme?.lowercased() else { return false }
- if scheme == "about" || scheme == "blob" || scheme == "data" { return true }
- guard scheme == "http" || scheme == "https" else { return false }
- guard let host = url.host?.lowercased() else { return false }
- if !isGooglePropertyHost(host) {
- return true
- }
- if isAllowedGoogleSignInHost(host, path: url.path) {
- return true
- }
- let path = url.path.lowercased()
- if host == "www.google.com", path.contains("/recaptcha") {
- return true
- }
- if host == "gstatic.com" || host.hasSuffix(".gstatic.com") {
- return true
- }
- return false
- }
- private static func isGooglePropertyHost(_ host: String) -> Bool {
- if host == "google.com" || host.hasSuffix(".google.com") { return true }
- if host == "gmail.com" || host.hasSuffix(".gmail.com") { return true }
- if host == "googleusercontent.com" || host.hasSuffix(".googleusercontent.com") { return true }
- if host == "gstatic.com" || host.hasSuffix(".gstatic.com") { return true }
- if host == "youtube.com" || host.hasSuffix(".youtube.com") { return true }
- if host == "blogger.com" || host.hasSuffix(".blogger.com") { return true }
- if host == "withgoogle.com" || host.hasSuffix(".withgoogle.com") { return true }
- return false
- }
- /// True for Google OAuth / sign-in navigations where we inject `prompt=select_account`.
- static func shouldForceGoogleAccountPicker(for url: URL) -> Bool {
- guard let host = url.host?.lowercased(),
- host == "accounts.google.com" || host.hasPrefix("accounts.google.") else {
- return false
- }
- let path = url.path.lowercased()
- if path.contains("oauth")
- || path.contains("accountchooser")
- || path.contains("/gsi/")
- || path.hasPrefix("/signin/") {
- return true
- }
- let query = url.query?.lowercased() ?? ""
- return query.contains("client_id=")
- }
- /// Rewrites Google sign-in URLs so the account chooser is always shown (not silent reuse of the last account).
- static func urlForcingGoogleAccountPicker(_ url: URL) -> URL {
- guard var components = URLComponents(url: url, resolvingAgainstBaseURL: false) else { return url }
- var items = components.queryItems ?? []
- items.removeAll { $0.name.compare("login_hint", options: .caseInsensitive) == .orderedSame }
- items.removeAll { $0.name.compare("hint", options: .caseInsensitive) == .orderedSame }
- if let promptIndex = items.firstIndex(where: { $0.name.compare("prompt", options: .caseInsensitive) == .orderedSame }) {
- let existing = items[promptIndex].value ?? ""
- if !existing.lowercased().contains("select_account") {
- let merged = existing.isEmpty ? "select_account" : "\(existing) select_account"
- items[promptIndex] = URLQueryItem(name: "prompt", value: merged)
- }
- } else {
- items.append(URLQueryItem(name: "prompt", value: "select_account"))
- }
- components.queryItems = items.isEmpty ? nil : items
- return components.url ?? url
- }
- /// Hosts used during “Sign in with Google” — not Help Center, Gmail, Drive, Search, or the apps launcher.
- private static func isAllowedGoogleSignInHost(_ host: String, path: String) -> Bool {
- if host == "accounts.google.com" || host.hasPrefix("accounts.google.") {
- return true
- }
- if host == "signin.google.com" {
- return true
- }
- if host == "oauth.googleusercontent.com" {
- return true
- }
- if host == "googleusercontent.com" || host.hasSuffix(".googleusercontent.com") {
- return true
- }
- if host == "policies.google.com" || host == "privacy.google.com" {
- return true
- }
- if host == "apis.google.com" {
- return true
- }
- return false
- }
- }
|