Access web browser tabs programmatically | Swift 3

偶尔善良 提交于 2019-12-06 01:29:05

Use an AppleScript to get the title and the URL of each tab.

You can use NSAppleScript in Swift to run an AppleScript.

An example (Safari)

let myAppleScript = "set r to \"\"\n" +
    "tell application \"Safari\"\n" +
    "repeat with w in windows\n" +
    "if exists current tab of w then\n" +
    "repeat with t in tabs of w\n" +
    "tell t to set r to r & \"Title : \" & name & \", URL : \" & URL & linefeed\n" +
    "end repeat\n" +
    "end if\n" +
    "end repeat\n" +
    "end tell\n" +
"return r"

var error: NSDictionary?
let scriptObject = NSAppleScript(source: myAppleScript)
if let output: NSAppleEventDescriptor = scriptObject?.executeAndReturnError(&error) {
    let titlesAndURLs = output.stringValue!
    print(titlesAndURLs)
} else if (error != nil) {
    print("error: \(error)")
}

The AppleScript return a string, like this:

Title : the title of the first tab, URL : the url of the first tab
Title : the title of the second tab, URL : the url of the second tab
Title : the title of the third tab, URL : the url of the third tab
....

An example (Google Chrome)

let myAppleScript = "set r to \"\"\n" +
    "tell application \"Google Chrome\"\n" +
    "repeat with w in windows\n" +
    "repeat with t in tabs of w\n" +
    "tell t to set r to r & \"Title : \" & title & \", URL : \" & URL & linefeed\n" +
    "end repeat\n" +
    "end repeat\n" +
    "end tell\n" +
"return r"
var error: NSDictionary?
let scriptObject = NSAppleScript(source: myAppleScript)
if let output: NSAppleEventDescriptor = scriptObject?.executeAndReturnError(&error) {
    let titlesAndURLs = output.stringValue!
    print(titlesAndURLs)
} else if (error != nil) {
    print("error: \(error)")
}

Update:

Here's the AppleScript with the comments.

You can run it in the "Script Editor" application.

set r to "" -- an empty variable for appending a string
tell application "Safari"
    repeat with w in windows -- loop for each window, w is a variable which contain the window object
        if exists current tab of w then --  is a valid browser window
            repeat with t in tabs of w -- loop for each tab of this window, , t is a variable which contain the tab object
                -- get the title (name) of this tab and get the url of this tab
                tell t to set r to r & "Title : " & name & ", URL : " & URL & linefeed -- append a line to the variable (r)
                (*
                 'linefeed'  mean a line break
                 'tell t' mean a tab of w (window)
                 '&'  is for  concatenate strings, same as the + operator in Swift
                *)
            end repeat
        end if
    end repeat
end tell
return r -- return the string (each line contains a title and an URL)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!