JSEventHelper.m 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. //
  2. // Helper.m
  3. // MacGap
  4. //
  5. // Created by Liam Kaufman Simpkins on 12-01-22.
  6. // Copyright (c) 2012 Twitter. All rights reserved.
  7. //
  8. #import "JSEventHelper.h"
  9. @implementation JSEventHelper
  10. + (void) triggerEvent:(NSString *)event forWebView:(WebView *)webView {
  11. [self triggerEvent:event withArgs:[NSMutableDictionary dictionary] forObject:@"document" forWebView:webView];
  12. }
  13. + (void) triggerEvent:(NSString *)event withArgs:(NSDictionary *)args forWebView:(WebView *)webView {
  14. [self triggerEvent:event withArgs:args forObject:@"document" forWebView:webView];
  15. }
  16. + (void) triggerEvent:(NSString *)event withArgs:(NSDictionary *)args forObject:(NSString *)objName forWebView:(WebView *)webView {
  17. // Convert args Dictionary to JSON.
  18. NSString* jsonString = [[Utils sharedInstance] convertDictionaryToJSON:args];
  19. // Create the event JavaScript and run it.
  20. NSString * str = [NSString stringWithFormat:@"var e = document.createEvent('Events'); e.initEvent('%@', true, false); e.data=%@; %@.dispatchEvent(e); ", event, jsonString, objName];
  21. [webView stringByEvaluatingJavaScriptFromString:str];
  22. }
  23. + (void) triggerEvent:(NSString *)event forDetail:(NSString *)detail forWebView:(WebView *)webView {
  24. [self triggerEvent:event forDetail:detail forObject:@"document" forWebView:webView];
  25. }
  26. + (void) triggerEvent:(NSString *)event forDetail:(NSString *)detail forObject:(NSString *)objName forWebView:(WebView *)webView {
  27. NSString *detailEscaped = [detail stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding];
  28. NSString *str = [NSString stringWithFormat:@"var e = new CustomEvent('%@', { 'detail': decodeURIComponent(\"%@\") }); %@.dispatchEvent(e); ", event, detailEscaped, objName];
  29. [webView stringByEvaluatingJavaScriptFromString:str];
  30. }
  31. @end