1

我正在尝试实现一个 safari 应用程序扩展,其中 safari 地址 bad 中的每个搜索都被重定向到另一个搜索引擎(在这种情况下,到 DuckDuckGo,仅作为示例)。我已经成功地做到了这一点。但是,使用此逻辑,如果用户打开www.google.com并在其搜索栏中进行搜索,该逻辑也会尝试重定向这些搜索。我该如何阻止这种情况发生?

//My SafariExtensionHandler file has the following functions:
//Given a Google, Yahoo, or Bing URL, this function will return the url encoding
func getQueryStringParameter(url: String) -> String? {
var param = "q"
if url.contains("search.yahoo.com") {
        param = "p"
    }
guard let url = URLComponents(string: url) else { return nil }
let rawString = url.queryItems?.first(where: { $0.name == param })?.value
let percentEncoding = rawString?.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)?.replacingOccurrences(of: "&", with: "%26")
return percentEncoding
}


// Before every page navigaion, this code checks if it's navigating to a search engine site. If so, it parses the url in order to instead navigate to that same seach term on DuckDuckGo.

override func page(_ page: SFSafariPage, willNavigateTo url: URL?) {
let hostnames = ["www.google.com", "www.bing.com", "search.yahoo.com"]
let url = url!
if hostnames.contains(url.host!) {
if let query = self.getQueryStringParameter(url: url.absoluteString) {
let redirectedURL = URL(string: "https://duckduckgo.com/?q=\(query)&ia=web")!
            page.getContainingTab { (tab) in
                tab.navigate(to: redirectedURL)
            }
        }
    }
}
4

0 回答 0