2016-10-02 7 views
0

SafariまたはGoogle Chromeの開いているタブにアクセスできますか? URLは良いか、タブのタイトルかその両方ですか?Webブラウザのタブにプログラムでアクセスする| Swift 3

ユーザーはいくつかのウェブサイトを指定してそれらにラベルを付けることができ、アプリはそれらのウェブサイトにどれくらいの金額が費やされているかを測定することができ、アクセシビリティによって許可されます。

答えて

2

AppleScriptを使用して、各タブのタイトルとURLを取得します。

SwiftでNSAppleScriptを使用してAppleScriptを実行できます。

例(サファリ

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 
.... 

例(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)") 
} 

更新:

ここでコメントした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) 
+0

これは素晴らしいです!私にコードの説明を教えてもらえますか?どの部分が何をしていますか? – user6879072

+0

私の答えに説明が追加されました – jackjr300

関連する問題