How to copy the current active browser URL?

前端 未结 3 1452
别跟我提以往
别跟我提以往 2020-12-29 16:49

I am trying to get the current active browser URL of the active browser window. Any pointers or code sample?

相关标签:
3条回答
  • 2020-12-29 17:30

    Solution in swift 5

    func getBrowserURL(_ appName: String) -> String? {
            guard let scriptText = getScriptText(appName) else { return nil }
            var error: NSDictionary?
            guard let script = NSAppleScript(source: scriptText) else { return nil }
    
            guard let outputString = script.executeAndReturnError(&error).stringValue else {
                if let error = error {
                    Logger.error("Get Browser URL request failed with error: \(error.description)")
                }
                return nil
            }
    
            // clean url output - remove protocol & unnecessary "www."
            if let url = URL(string: outputString),
                var host = url.host {
                if host.hasPrefix("www.") {
                    host = String(host.dropFirst(4))
                }
                let resultURL = "\(host)\(url.path)"
                return resultURL
            }
    
            return nil
        }
    
        func getScriptText(_ appName: String) -> String? {
            switch appName {
            case "Google Chrome":
                return "tell app \"Google Chrome\" to get the url of the active tab of window 1"
            case "Safari":
                return "tell application \"Safari\" to return URL of front document"
            default:
                return nil
            }
        }
    
    0 讨论(0)
  • 2020-12-29 17:32

    Code:

    NSAppleScript *script= [[NSAppleScript alloc] initWithSource:@"tell application \"Safari\" to return URL of front document as string"];
    NSDictionary *scriptError = nil;
    NSAppleEventDescriptor *descriptor = [script executeAndReturnError:&scriptError];
    if(scriptError) {
        NSLog(@"Error: %@",scriptError);
    } else {        
        NSAppleEventDescriptor *unicode = [descriptor coerceToDescriptorType:typeUnicodeText];
        NSData *data = [unicode data];
        NSString *result = [[NSString alloc] initWithCharacters:(unichar*)[data bytes] length:[data length] / sizeof(unichar)];
        NSLog(@"Result: %@",result);
    }
    

    Output:

    Result: http://stackoverflow.com/questions/6111275/how-to-copy-the-current-active-browser-url/6111592#6111592
    
    0 讨论(0)
  • 2020-12-29 17:42

    I would think it would have to be done via Applescript, if the browser exposes such information in its dictionary.

    The following URL gives some useful examples of how to call Applescript from Objective-C: Objective-C & Applescript

    0 讨论(0)
提交回复
热议问题