I'm making an action extension for safari and I need to get the selected text for use inside the extension.
Usually in iOS i use this code to get the selected text in a webview
selectedText.text = [WebView stringByEvaluatingJavaScriptFromString: @ "window.getSelection (). toString ()"];
But inside the extension i don't know how can I do !
For completeness it should be an extension with IU and i've just to turn on NSExtensionActivationSupportsWebURLWithMaxCount to make extension available in Safari.
Thanks in advance
As Apple explains in their App Extension Programming Guide, you need to include a JavaScript file in the extension to perform any preprocessing. The results of that preprocessing are available via NSExtensionItem
in the extension.
A simple example of this file is included in my iOS Extension Demo project at GitHub and looks like this:
var MyPreprocessor = function() {};
MyPreprocessor.prototype = {
run: function(arguments) {
arguments.completionFunction({"URL": document.URL, "pageSource": document.documentElement.outerHTML, "title": document.title, "selection": window.getSelection().toString()});
}
};
var ExtensionPreprocessingJS = new MyPreprocessor;
That simply extracts various details about the current page and passes them to completionFunction
. The ExtensionPreprocessingJS
var at the end is the hook that the extension framework looks for.
In the extension you can retrieve these values in a dictionary by asking for an item of type kUTTypePropertyList
:
for (NSExtensionItem *item in self.extensionContext.inputItems) {
for (NSItemProvider *itemProvider in item.attachments) {
if ([itemProvider hasItemConformingToTypeIdentifier:(NSString *)kUTTypePropertyList]) {
[itemProvider loadItemForTypeIdentifier:(NSString *)kUTTypePropertyList options:nil completionHandler:^(NSDictionary *jsDict, NSError *error) {
dispatch_async(dispatch_get_main_queue(), ^{
NSDictionary *jsPreprocessingResults = jsDict[NSExtensionJavaScriptPreprocessingResultsKey];
// Continue with data returned from JS...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With