Skip to content

Instantly share code, notes, and snippets.

@iFwu
Last active May 23, 2019 11:08
Show Gist options
  • Save iFwu/d43546352696ba22507a61bf8818c60e to your computer and use it in GitHub Desktop.
Save iFwu/d43546352696ba22507a61bf8818c60e to your computer and use it in GitHub Desktop.
Seach Selected Text in JavaScript Mac Automation Scripting
function validURL(str) {
var pattern = new RegExp(
'^(https?:\\/\\/)?' + // protocol
'((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.)+[a-z]{2,}|' + // domain name
'((\\d{1,3}\\.){3}\\d{1,3}))' + // OR ip (v4) address
'(\\:\\d+)?(\\/[-a-z\\d%_.~+]*)*' + // port and path
'(\\?[;&a-z\\d%_.~+=-]*)?' + // query string
'(\\#[-a-z\\d_]*)?$',
'i'
); // fragment locator
return !!pattern.test(str);
}
function run(input) {
var safari = Application('Safari');
var chrome = Application('Google Chrome');
var isSafariFront = safari.frontmost();
var isChromeFront = chrome.frontmost();
if (!isChromeFront) {
try {
chrome = Application('Google Chrome Canary');
isChromeFront = chrome.frontmost();
} catch (e) {}
}
if (!isSafariFront && !isChromeFront) {
safari.activate();
}
var runScript = js => {
if (isChromeFront) {
chrome.windows[0].activeTab.execute({ javascript: js });
return;
}
safari.doJavaScript(js, { in: safari.windows[0].currentTab });
};
var url = String(input).trim();
var isUrl = validURL(url);
if (isUrl && !/^http/.test(url)) {
url = `http:\/\/${url}`;
}
if (!isUrl) {
url = `https://www.google.com/search?client=safari&rls=en&q=${url}&ie=UTF-8&oe=UTF-8`;
}
runScript(`
var aLink = document.createElement('a')
aLink.style.cssText = 'display:none;width:0px;height:0px;'
aLink.href = encodeURI(unescape('${escape(url)}'));
aLink.target = '_blank'
document.body.appendChild(aLink)
aLink.click()
`);
return input;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment