Get selected text in Safari and use it in extension actions

I am doing an action extension for safari, and I need to get selected text to use inside the extension.

Usually on iOS, I use this code to get selected text in a webview

selectedText.text = [WebView stringByEvaluatingJavaScriptFromString: @ "window.getSelection (). toString ()"]; 

But inside the extension, I don’t know how I can do this!

For completeness, this must be an extension using the IU, and I must enable NSExtensionActivationSupportsWebURLWithMaxCount to make the extension available in Safari.

Thank you in advance

+6
source share
2 answers

As Apple explains in her guide on programming application extensions , you need to include a JavaScript file in the extension to do any preprocessing. The results of this preprocessing are available through the NSExtensionItem extension.

A simple example of this file is included in my iOS Extension Demo project on 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; 

It simply extracts various details about the current page and passes their completionFunction . ExtensionPreprocessingJS var at the end is the hook that the extension infrastructure is looking for.

In the extension, you can get these values ​​in the dictionary by kUTTypePropertyList an element 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... 
+7
source

You may need to execute the .js file to complete this operation.

I suggest you direct this Extension Tutorial , which is almost similar to your requirement.

0
source

Source: https://habr.com/ru/post/979256/


All Articles