gpt4 book ai didi

macos - 以编程方式访问网络浏览器选项卡 | swift 3

转载 作者:行者123 更新时间:2023-12-01 12:25:51 25 4
gpt4 key购买 nike

是否可以访问 Safari 或 Google Chrome 打开的标签页?一个 URL 或选项卡的标题或两者都好?

应用程序的用途然后用户可以指定一些网站并为它们添加标签,应用程序将衡量在这些网站上花费了多少,应用程序将通过辅助功能被允许。

最佳答案

使用 AppleScript 获取每个选项卡的标题和 URL。

您可以在 Swift 中使用 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)

关于macos - 以编程方式访问网络浏览器选项卡 | swift 3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39818320/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com