假设我有一个名为的可执行文件my_link_opener
,如何将其设置为默认浏览器?
我已经尝试了以下方法,但没有成功:
我尝试使用Appify将其包装为.app,然后将生成的.app设置为Safari中的默认浏览器。
但是,由于OS X期望程序只有一个“实例”在其生命周期中打开许多链接,所以这行不通。
而不是在命令行上传递URL,它发送一个-psn_xxxxx
参数。
用Automator进行包装
事实证明,如果将其添加为Automator中的工作流,则可以使其以打开的文件作为参数。
但是,这仅适用于文件和文件夹。
据我所知,没有办法使URL对Automator工作流有效。
所以,我很不幸。我还能做其他包装魔术吗?
我找不到任何已经存在的选项(但仍有可能存在),所以我最终写了一个。基本上,它的作用是告诉系统该应用程序是浏览器,最终将其自身设置为默认浏览器(请参阅参考资料#define SET_AS_DEFAULT_BROWSER
),并在接收到正确的事件时最终通过将url发送到my_link_opener
位于应用程序包中的脚本来管理url (即是在.app目录中)。bash命令称为:
nohup /path/to/my_link_opener "_an_url_" >& /dev/null &
#import "ZFTAppDelegate.h"
NSString *runCommand(NSString *commandToRun)
{
NSTask *task;
task = [[NSTask alloc] init];
[task setLaunchPath: @"/bin/sh"];
NSArray *arguments = @[@"-c" ,[NSString stringWithFormat:@"%@", commandToRun]];
[task setArguments: arguments];
NSPipe *pipe;
pipe = [NSPipe pipe];
[task setStandardOutput: pipe];
NSFileHandle *file;
file = [pipe fileHandleForReading];
[task launch];
NSData *data;
data = [file readDataToEndOfFile];
NSString *output;
output = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
return output;
}
#define SET_AS_DEFAULT_BROWSER
@implementation ZFTAppDelegate
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
NSAppleEventManager *em = [NSAppleEventManager sharedAppleEventManager];
[em setEventHandler:self
andSelector:@selector(getUrl:withReplyEvent:)
forEventClass:kInternetEventClass
andEventID:kAEGetURL];
[em setEventHandler:self
andSelector:@selector(getUrl:withReplyEvent:)
forEventClass:'WWW!'
andEventID:'OURL'];
#ifdef SET_AS_DEFAULT_BROWSER
CFStringRef bundleID = (__bridge CFStringRef)[[NSBundle mainBundle] bundleIdentifier];
LSSetDefaultHandlerForURLScheme(CFSTR("http"), bundleID);
LSSetDefaultHandlerForURLScheme(CFSTR("https"), bundleID);
#endif
}
- (void)getUrl:(NSAppleEventDescriptor *)event withReplyEvent:(NSAppleEventDescriptor *)replyEvent
{
NSString *url = [[event paramDescriptorForKeyword:keyDirectObject] stringValue];
NSString* scriptPath = [[[NSBundle mainBundle] bundlePath] stringByAppendingPathComponent:@"my_link_opener"];
runCommand([NSString stringWithFormat:@"nohup %@ \"%@\" >& /dev/null &", scriptPath, url]);
}
@end
请记住,您应该在应用程序的info.plist中拥有此功能(需要通知操作系统有关您的应用程序处理http / s url的功能):
<key>CFBundleURLTypes</key>
<array>
<dict>
<key>CFBundleURLSchemes</key>
<array>
<string>https</string>
</array>
<key>CFBundleURLName</key>
<string>Secure http URL</string>
</dict>
<dict>
<key>CFBundleURLSchemes</key>
<array>
<string>http</string>
</array>
<key>CFBundleURLName</key>
<string>http URL</string>
</dict>
</array>
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句