Skip to content

Instantly share code, notes, and snippets.

@zorgiepoo
Last active October 21, 2023 07:54
Show Gist options
  • Save zorgiepoo/d751cba19a0167a589a2 to your computer and use it in GitHub Desktop.
Save zorgiepoo/d751cba19a0167a589a2 to your computer and use it in GitHub Desktop.
Example program for retrieving active URLs from Safari webkit processes.
#import <Foundation/Foundation.h>
// Useful references:
// -[SMProcess webKitActiveURLs] implementation used in Activity Monitor on 10.9 (search for it using Hopper)
// http://opensource.apple.com/source/WebKit2/WebKit2-7537.71/WebProcess/mac/WebProcessMac.mm
// https://github.com/rodionovd/RDProcess/blob/master/RDProcess.m
const CFStringRef kLSActivePageUserVisibleOriginsKey = CFSTR("LSActivePageUserVisibleOriginsKey");
const int kLSMagicConstant = -1;
extern CFTypeRef _LSCopyApplicationInformationItem(int /* hopefully */, CFTypeRef, CFStringRef);
extern CFTypeRef _LSASNCreateWithPid(CFAllocatorRef, pid_t);
// Returns an array of active URLs (as strings) from a safari webkit process identifier, or nil on failure
// Need to be running as root for this to work
static NSArray *webKitActiveURLs(pid_t webKitProcessIdentifier)
{
NSArray *urlStrings = nil;
CFTypeRef asn = _LSASNCreateWithPid(kCFAllocatorDefault, webKitProcessIdentifier);
if (asn != NULL)
{
id information = CFBridgingRelease(_LSCopyApplicationInformationItem(kLSMagicConstant, asn, kLSActivePageUserVisibleOriginsKey));
// since Activity Monitor's -[SMProcess webKitActiveURLs] does a type check, we may as well too
if ([information isKindOfClass:[NSString class]])
{
urlStrings = @[information];
}
else if ([information isKindOfClass:[NSArray class]])
{
urlStrings = information;
}
CFRelease(asn);
}
return urlStrings;
}
int main(int argc, const char * argv[])
{
@autoreleasepool
{
if (argc != 2)
{
printf("Supply a process identifier for a \"Safari Web Content\" process\n");
exit(1);
}
pid_t processIdentifier = atoi(argv[1]);
NSArray *webKitURLs = webKitActiveURLs(processIdentifier);
if (webKitURLs == nil)
{
printf("Active URLs retrieval failed. Is %d a valid identifier, and are you running as root?\n", processIdentifier);
exit(2);
}
for (NSString *webKitURL in webKitURLs)
{
printf("%s\n", [webKitURL UTF8String]);
}
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment