0
是否可以訪問Safari或Google Chrome的打開標籤頁? URL是好還是標籤的標題或兩者?以編程方式訪問Web瀏覽器選項卡| Swift 3
該應用的目的,那麼用戶可以指定一些網站和標籤添加到他們的應用程序將測量有多少是花在這些網站,應用程序將通過輔助功能被允許。
是否可以訪問Safari或Google Chrome的打開標籤頁? URL是好還是標籤的標題或兩者?以編程方式訪問Web瀏覽器選項卡| Swift 3
該應用的目的,那麼用戶可以指定一些網站和標籤添加到他們的應用程序將測量有多少是花在這些網站,應用程序將通過輔助功能被允許。
使用AppleScript獲取每個選項卡的標題和URL。
您可以使用NSAppleScript
在斯威夫特運行AppleScript。
一個例子(的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)")
}
的的AppleScript返回一個字符串,象這樣:
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 ....
一個例子(谷歌瀏覽器)
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)")
}
更新:
這裏的的AppleScript與評論。
您可以在「腳本編輯器」應用程序運行它。
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)
這是偉大的!你介意給我一些關於代碼的解釋,哪部分是做什麼的? – user6879072
我在答案中加入瞭解釋 – jackjr300