I am trying to implement a safari app extension where every search in the safari address bad gets redirected to another search engine(in this care, to DuckDuckGo, just as an example). I have managed to do this much. However, using this logic, if the user opens www.google.com and searches in their search bar, the logic tries to redirect those searches as well. How do I stop that from happening?
//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)
}
}
}
}