Possible to get a text selection out from safari (host app)to an app extension, or only the URL?
Asked
Active
Viewed 599 times
1 Answers
3
Yes this is possible. You can create a JavaScript file as part of your Action Extension. This is described in the documentation since you also have to add a NSExtensionJavaScriptPreprocessingFile
key to your extension's Info.plist.
Inside the JavaScript file you can define a run
function which allows you to define values to pass to your native extension code. Here you can get the selected text as shown in other questions and pass this through to your extension.
Here's a quick example of how this might work on the JavaScript side:
var MyExtensionJavaScriptClass = function() {};
MyExtensionJavaScriptClass.prototype = {
run: function(arguments) {
// Pass the selected text through
arguments.completionFunction({"text": window.getSelection().toString()});
}
};
// The JavaScript file must contain a global object named "ExtensionPreprocessingJS".
var ExtensionPreprocessingJS = new MyExtensionJavaScriptClass;

Community
- 1
- 1

Keith Smiley
- 61,481
- 12
- 97
- 110
-
I just tried creating an action extension with Xcode 6.2b2 and there is no `Action.js` file. What steps do you take that causes Xcode to include that file? – Tom Harrington Jan 05 '15 at 18:07
-
This is part of the default template in Xcode 6.1.1. You can add these files yourself if you'd prefer. See [here](https://developer.apple.com/library/ios/documentation/General/Conceptual/ExtensibilityPG/Services.html) for the Info.plist changes you'll need to make as well. – Keith Smiley Jan 05 '15 at 18:18
-
What I'm saying is that it's not part of the template, when I try it. If I add an action extension, the template created by Xcode does not contain that file. That page also does not indicate that the file is included as part of the template. If you are seeing this happen, please describe what you're doing in more detail, because I can't get Xcode to do it. – Tom Harrington Jan 05 '15 at 18:20
-
Since it isn't in the template for you just create the js file yourself. Then add the relevant keys to your Info.plist as described in the linked documentation. – Keith Smiley Jan 05 '15 at 18:23
-
You should update your answer so that it does not claim that this is automatically included. – Tom Harrington Jan 05 '15 at 18:24
-
Ah yep it looks like this must have been removed in 6.1.1 and it was generated with 6.1. – Keith Smiley Jan 05 '15 at 18:26