我发现了这个工具。安装完成后,你可以做到以下操作:
defaultbrowser chrome
为了防止链接在未来出现404错误
,以下是整个源代码。该源代码受2014年Margus Kerma版权下的MIT许可证保护。
#import <Foundation/Foundation.h>
#import <ApplicationServices/ApplicationServices.h>
NSString* app_name_from_bundle_id(NSString *app_bundle_id) {
return [[app_bundle_id componentsSeparatedByString:@"."] lastObject];
}
NSMutableDictionary* get_http_handlers() {
NSArray *handlers =
(__bridge NSArray *) LSCopyAllHandlersForURLScheme(
(__bridge CFStringRef) @"http"
);
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
for (int i = 0; i < [handlers count]; i++) {
NSString *handler = [handlers objectAtIndex:i];
dict[[app_name_from_bundle_id(handler) lowercaseString]] = handler;
}
return dict;
}
NSString* get_current_http_handler() {
NSString *handler =
(__bridge NSString *) LSCopyDefaultHandlerForURLScheme(
(__bridge CFStringRef) @"http"
);
return app_name_from_bundle_id(handler);
}
void set_default_handler(NSString *url_scheme, NSString *handler) {
LSSetDefaultHandlerForURLScheme(
(__bridge CFStringRef) url_scheme,
(__bridge CFStringRef) handler
);
}
int main(int argc, const char *argv[]) {
const char *target = (argc == 1) ? '\0' : argv[1];
@autoreleasepool {
// Get all HTTP handlers
NSMutableDictionary *handlers = get_http_handlers();
// Get current HTTP handler
NSString *current_handler_name = get_current_http_handler();
if (target == '\0') {
// List all HTTP handlers, marking the current one with a star
for (NSString *key in handlers) {
char *mark = [key isEqual:current_handler_name] ? "* " : " ";
printf("%s%s\n", mark, [key UTF8String]);
}
} else {
NSString *target_handler_name = [NSString stringWithUTF8String:target];
if ([target_handler_name isEqual:current_handler_name]) {
printf("%s is already set as the default HTTP handler\n", target);
} else {
NSString *target_handler = handlers[target_handler_name];
if (target_handler != nil) {
// Set new HTTP handler (HTTP and HTTPS separately)
set_default_handler(@"http", target_handler);
set_default_handler(@"https", target_handler);
} else {
printf("%s is not available as an HTTP handler\n", target);
return 1;
}
}
}
}
return 0;
}
Makefile:
BIN ?= defaultbrowser
PREFIX ?= /usr/local
BINDIR ?= $(PREFIX)/bin
CC = gcc
CFLAGS = -O2
.PHONY: all install uninstall clean
all:
gcc -o $(BIN) $(CFLAGS) -framework Foundation -framework ApplicationServices src/main.m
install: all
install -d $(BINDIR)
install -m 755 $(BIN) $(BINDIR)
uninstall:
rm -f $(BINDIR)/$(BIN)
clean:
rm -f $(BIN)
brew install defaultbrowser
。 - james-see我知道这并没有直接回答你的问题,但是如果你只需要在Chrome上这么做,它有一个标志可以让你将其设置为默认浏览器:
$ open -a "Google Chrome" --args --make-default-browser
对于新版 macOS(Catalina,Big Sur),我使用 Swift 重新实现了默认浏览器工具(称为 defbro)。主要原因是使用一种“现代”的编程语言,可以让我轻松调整和改进它。我还添加了 json 输出 defbro --json
,以便您可以在其中执行其他操作。
安装:brew install jwbargsten/misc/defbro
唯一的方法是在主设置中进行设置:
defaultbrowser brave
的错误,提示“brave 不可用作 HTTP 处理程序”。 - volvoxbrew install defaultbrowser
是正确的方法。如果你想要 Brave 浏览器,使用defaultbrowser browser
。 - volvox