1

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)
            }
        }
    }
}
onetrueshady
  • 175
  • 1
  • 10
  • Are you aware that this finctionality is provided in the iOS Settings for Safari under 'Search Engine? And 'DuckDuckGo' is listed too! – multitudes Nov 06 '20 at 11:46
  • Yes. But DuckDuckGo is just an example. I am asking on a general term. Like what if I wanted to change it to Ecosia, for example. In fact, Ecosia have an extension where they have implemented it. – onetrueshady Nov 06 '20 at 15:27

0 Answers0