I want to save the state where the user left the webView (which is loading a local html file) so that the next time when he enters the same view, he is taken to the same line of text that he was reading the previous time.
I think that could be achieved by saving the scroll value in an integer every time the user swipe the document, and when he enters the view the next time we use the value that was saved previously and scroll the view using a javascript command or "CG" things.
Any idea?
and an objective c solution:
#interface ViewController () <UIWebViewDelegate>
#property (weak, nonatomic) IBOutlet UIWebView *webView;
#end
#implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
[self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:#"http://yourwebsite.com"]]];
}
- (void)webViewDidFinishLoad:(UIWebView *)webView {
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
if ([userDefaults objectForKey:#"contentOffset"]) {
webView.scrollView.contentOffset = CGPointFromString([userDefaults objectForKey:#"contentOffset"]);
}
}
- (void)viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:animated];
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
[userDefaults setObject:NSStringFromCGPoint(self.webView.scrollView.contentOffset) forKey:#"contentOffset"];
[userDefaults synchronize];
}
From Lyndsey Scott's Answer:
To save and retrieve your scrollview offset from NSUserDefaults, set your UIWebView's delegate and try this:
var viewLaidoutSubviews = false // <-- variable to prevent the viewDidLayoutSubviews code from happening more than once
// Save your content offset when the view disappears
override func viewWillDisappear(animated: Bool) {
var userDefaults = NSUserDefaults.standardUserDefaults()
userDefaults.setValue(NSStringFromCGPoint(myBrowser.scrollView.contentOffset), forKey: "scroll_offset")
userDefaults.synchronize()
viewLaidoutSubviews = false
}
// Retrieve and set your content offset when the view re-appears
// and its subviews are first laid out
override func viewDidLayoutSubviews() {
if (!viewLaidoutSubviews) {
// If a scroll_offset is store in NSUserDefaults, use it
var userDefaults = NSUserDefaults.standardUserDefaults()
var scrollOffset:CGPoint? = CGPointFromString(userDefaults.valueForKey("scroll_offset") as? NSString)
if let position:CGPoint = scrollOffset {
myBrowser.scrollView.delegate = self
myBrowser.scrollView.setContentOffset(position, animated: false)
}
viewLaidoutSubviews = true
}
}
And utilize your UIWebView's webViewDidFinishLoad delegate method to update the scroll offset in the case that the web view didn't finish rendering before the view laid out its subviews:
// Retrieve and set your content offset once the web view has
// finished rendering (in case it hasn't finished rendering
// by the time the view's subviews were laid out)
func webViewDidFinishLoad(webView: UIWebView) {
// If a scroll_offset is store in NSUserDefaults, use it
var userDefaults = NSUserDefaults.standardUserDefaults()
var scrollOffset:CGPoint? = CGPointFromString(userDefaults.valueForKey("scroll_offset") as? NSString)
if let position:CGPoint = scrollOffset {
myBrowser.scrollView.delegate = self
myBrowser.scrollView.setContentOffset(position, animated: true)
}
}
But note, your NSUserDefaults value will also persist between app launches unless you delete it.
Related
I work on a native Objective-C library and I'm exposing some of the API into JavaScript. The purpose is to make it accessible on both Android and iOS
On iOS, I use JSContext and JSExport as described here
Objective-C
#import JavaScriptCore;
#protocol PersonExports <JSExport>
+ (void)sayHello:(NSString *)name;
#end
#interface Person : NSObject
+ (void)sayHello:(NSString *)name;
#end
Then I add the exposed object to the JSContext of a UIWebView when it finishes loading:
JSContext *context = [self.webView valueForKeyPath:#"documentView.webView.mainFrame.javaScriptContext"];
if (nil != context) {
context[#"Person"] = [Person class];
}
After this, I can access the object from the JavaScript in the loaded page and call the method on it:
JavaScript
<script type="text/javascript">
Person.sayHello(#"Mickey");
</script>
The question is how can I achieve this in a WKWebView?
// Create a WKWebView instance
self.webView = [[WKWebView alloc]initWithFrame:self.view.frame configuration:self.webConfig];
// Delegate to handle navigation of web content
self.webView.navigationDelegate = self;
[self.view addSubview:self.webView];
setup accessor for self.webConfig
#pragma mark - accessors
-(WKWebViewConfiguration*) webConfig {
if (!_webConfig) {
// Create WKWebViewConfiguration instance
_webConfig = [[WKWebViewConfiguration alloc]init];
// Setup WKUserContentController instance for injecting user script
WKUserContentController* userController = [[WKUserContentController alloc]init];
// Add a script message handler for receiving "buttonClicked" event notifications posted from the JS document using window.webkit.messageHandlers.buttonClicked.postMessage script message
[userController addScriptMessageHandler:self name:#"buttonClicked"];
// Get script that's to be injected into the document
NSString* js = [self buttonClickEventTriggeredScriptToAddToDocument];
// Specify when and where and what user script needs to be injected into the web document
WKUserScript* userScript = [[WKUserScript alloc]initWithSource:js injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:NO];
// Add the user script to the WKUserContentController instance
[userController addUserScript:userScript];
// Configure the WKWebViewConfiguration instance with the WKUserContentController
_webConfig.userContentController = userController;
}
return _webConfig;
}
implement script message handler method from protocol
#pragma mark -WKScriptMessageHandler
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
if ([message.name isEqualToString:#"buttonClicked"]) {
self.buttonClicked ++;
}
// JS objects are automatically mapped to ObjC objects
id messageBody = message.body;
if ([messageBody isKindOfClass:[NSDictionary class]]) {
NSString* idOfTappedButton = messageBody[#"ButtonId"];
[self updateColorOfButtonWithId:idOfTappedButton];
}
}
and post the message form js like this
var button = document.getElementById("clickMeButton");
button.addEventListener("click", function() {
var messgeToPost = {'ButtonId':'clickMeButton'};
window.webkit.messageHandlers.buttonClicked.postMessage(messgeToPost);
},false);
this will help you because i also faced this issue while setting context nad calling method form JSExport
I have the following problem, I need to disable the native Keyboard completely. The keyboard should only show when I call the show() and hide when I call the close() function (this will be on a Button for the user to toggle the Keyboard).
The Keyboard showing on clicking the Field and on Focus needs to be completely disabled.
On Stackoverflow I found this:
InputMethodManager im = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
im.hideSoftInputFromWindow(editText.getWindowToken(), 0);
So my thought was In the "Init"(Line 52 in the IonicKeyboard.java) I need to change it.
if ("init".equals(action)) {
cordova.getThreadPool().execute(new Runnable() {
public void run() {
//new Logic on init
View v = cordova.getActivity().getCurrentFocus();
((InputMethodManager) cordova.getActivity().getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(v.getWindowToken(), 0);
DisplayMetrics dm = new DisplayMetrics();
cordova.getActivity().getWindowManager().getDefaultDisplay().getMetrics(dm);
final float density = dm.density;
//http://stackoverflow.com/a/4737265/1091751 detect if keyboard is showing
final View rootView = cordova.getActivity().getWindow().getDecorView().findViewById(android.R.id.content).getRootView();
OnGlobalLayoutListener list = new OnGlobalLayoutListener() {
int previousHeightDiff = 0;
#Override
public void onGlobalLayout() {
Rect r = new Rect();
//r will be populated with the coordinates of your view that area still visible.
rootView.getWindowVisibleDisplayFrame(r);
PluginResult result;
int heightDiff = rootView.getRootView().getHeight() - r.bottom;
int pixelHeightDiff = (int)(heightDiff / density);
if (pixelHeightDiff > 100 && pixelHeightDiff != previousHeightDiff) { // if more than 100 pixels, its probably a keyboard...
String msg = "S" + Integer.toString(pixelHeightDiff);
result = new PluginResult(PluginResult.Status.OK, msg);
result.setKeepCallback(true);
callbackContext.sendPluginResult(result);
}
else if ( pixelHeightDiff != previousHeightDiff && ( previousHeightDiff - pixelHeightDiff ) > 100 ){
String msg = "H";
result = new PluginResult(PluginResult.Status.OK, msg);
result.setKeepCallback(true);
callbackContext.sendPluginResult(result);
}
previousHeightDiff = pixelHeightDiff;
}
};
rootView.getViewTreeObserver().addOnGlobalLayoutListener(list);
PluginResult dataResult = new PluginResult(PluginResult.Status.OK);
dataResult.setKeepCallback(true);
callbackContext.sendPluginResult(dataResult);
}
});
return true;
}
return false; // Returning false results in a "MethodNotFound" error.
}
Sadly this does not work at all...
I think I have to change the close / show function too but I am not really sure what the correct code is, and I dont know if this change would affect other Keyboard behaviour. (But I basically need Focus without Keyboard)
I also found this Cordova Plugin
which looks very promising, but I decided to change this in the Ionic Keyboard Plugin, because I need the same behaviour in Windows too.
Very glad if someone could help me out here.
Regards Christopher
This can be accomplished by disabling all inputs with ng-disabled and later showing the keyboard with the Ionic Keyboard Plugin.
If you do not want the inputs to appear differently when disabled, you can override this style with CSS using the :disabled selector.
Hide on load:
<input ng-disabled="hideKeyboard">
hideKeyboard = true;
Show on function:
<input ng-disabled="hideKeyboard">
function showKeyboard(){
hideKeyboard = false;
cordova.plugins.Keyboard.show();
}
In Firefox, at the start of modules/devtools/inspector/inspector-panel.js you see some references to a "walker", shown at the end of this snippet:
...
/**
* Represents an open instance of the Inspector for a tab.
* The inspector controls the highlighter, the breadcrumbs,
* the markup view, and the sidebar (computed view, rule view
* and layout view).
*
* Events:
* - ready
* Fired when the inspector panel is opened for the first time and ready to
* use
* - new-root
* Fired after a new root (navigation to a new page) event was fired by
* the walker, and taken into account by the inspector (after the markup
* view has been reloaded)
* - markuploaded
* Fired when the markup-view frame has loaded
* - layout-change
* Fired when the layout of the inspector changes
* - breadcrumbs-updated
* Fired when the breadcrumb widget updates to a new node
* - layoutview-updated
* Fired when the layoutview (box model) updates to a new node
* - markupmutation
* Fired after markup mutations have been processed by the markup-view
* - computed-view-refreshed
* Fired when the computed rules view updates to a new node
* - computed-view-property-expanded
* Fired when a property is expanded in the computed rules view
* - computed-view-property-collapsed
* Fired when a property is collapsed in the computed rules view
* - rule-view-refreshed
* Fired when the rule view updates to a new node
*/
function InspectorPanel(iframeWindow, toolbox) {
this._toolbox = toolbox;
this._target = toolbox._target;
this.panelDoc = iframeWindow.document;
this.panelWin = iframeWindow;
this.panelWin.inspector = this;
this._inspector = null;
this._onBeforeNavigate = this._onBeforeNavigate.bind(this);
this._target.on("will-navigate", this._onBeforeNavigate);
EventEmitter.decorate(this);
}
exports.InspectorPanel = InspectorPanel;
InspectorPanel.prototype = {
/**
* open is effectively an asynchronous constructor
*/
open: function InspectorPanel_open() {
return this.target.makeRemote().then(() => {
return this._getWalker();
}).then(() => {
return this._getDefaultNodeForSelection();
}).then(defaultSelection => {
return this._deferredOpen(defaultSelection);
}).then(null, console.error);
},
get inspector() {
if (!this._target.form) {
throw new Error("Target.inspector requires an initialized remote actor.");
}
if (!this._inspector) {
this._inspector = InspectorFront(this._target.client, this._target.form);
}
return this._inspector;
},
_deferredOpen: function(defaultSelection) {
let deferred = promise.defer();
this.outerHTMLEditable = this._target.client.traits.editOuterHTML;
this.onNewRoot = this.onNewRoot.bind(this);
this.walker.on("new-root", this.onNewRoot);
this.nodemenu = this.panelDoc.getElementById("inspector-node-popup");
this.lastNodemenuItem = this.nodemenu.lastChild;
this._setupNodeMenu = this._setupNodeMenu.bind(this);
this._resetNodeMenu = this._resetNodeMenu.bind(this);
this.nodemenu.addEventListener("popupshowing", this._setupNodeMenu, true);
this.nodemenu.addEventListener("popuphiding", this._resetNodeMenu, true);
// Create an empty selection
this._selection = new Selection(this.walker);
this.onNewSelection = this.onNewSelection.bind(this);
this.selection.on("new-node-front", this.onNewSelection);
this.onBeforeNewSelection = this.onBeforeNewSelection.bind(this);
this.selection.on("before-new-node-front", this.onBeforeNewSelection);
this.onDetached = this.onDetached.bind(this);
this.selection.on("detached-front", this.onDetached);
this.breadcrumbs = new HTMLBreadcrumbs(this);
if (this.target.isLocalTab) {
this.browser = this.target.tab.linkedBrowser;
this.scheduleLayoutChange = this.scheduleLayoutChange.bind(this);
this.browser.addEventListener("resize", this.scheduleLayoutChange, true);
// Show a warning when the debugger is paused.
// We show the warning only when the inspector
// is selected.
this.updateDebuggerPausedWarning = function() {
let notificationBox = this._toolbox.getNotificationBox();
let notification = notificationBox.getNotificationWithValue("inspector-script-paused");
if (!notification && this._toolbox.currentToolId == "inspector" &&
this.target.isThreadPaused) {
let message = this.strings.GetStringFromName("debuggerPausedWarning.message");
notificationBox.appendNotification(message,
"inspector-script-paused", "", notificationBox.PRIORITY_WARNING_HIGH);
}
if (notification && this._toolbox.currentToolId != "inspector") {
notificationBox.removeNotification(notification);
}
if (notification && !this.target.isThreadPaused) {
notificationBox.removeNotification(notification);
}
}.bind(this);
this.target.on("thread-paused", this.updateDebuggerPausedWarning);
this.target.on("thread-resumed", this.updateDebuggerPausedWarning);
this._toolbox.on("select", this.updateDebuggerPausedWarning);
this.updateDebuggerPausedWarning();
}
this.highlighter = new Highlighter(this.target, this, this._toolbox);
let button = this.panelDoc.getElementById("inspector-inspect-toolbutton");
this.onLockStateChanged = function() {
if (this.highlighter.locked) {
button.removeAttribute("checked");
this._toolbox.raise();
} else {
button.setAttribute("checked", "true");
}
}.bind(this);
this.highlighter.on("locked", this.onLockStateChanged);
this.highlighter.on("unlocked", this.onLockStateChanged);
this._initMarkup();
this.isReady = false;
this.once("markuploaded", function() {
this.isReady = true;
// All the components are initialized. Let's select a node.
this._selection.setNodeFront(defaultSelection);
this.markup.expandNode(this.selection.nodeFront);
this.emit("ready");
deferred.resolve(this);
}.bind(this));
this.setupSearchBox();
this.setupSidebar();
return deferred.promise;
},
_onBeforeNavigate: function() {
this._defaultNode = null;
this.selection.setNodeFront(null);
this._destroyMarkup();
this.isDirty = false;
},
_getWalker: function() {
return this.inspector.getWalker().then(walker => {
this.walker = walker;
return this.inspector.getPageStyle();
}).then(pageStyle => {
this.pageStyle = pageStyle;
});
},
...
I didn't see this Promise documented anywhere in the Addon APIs, is there any documentation (or even source comments) on what this is, and how it is used?
Could it be used to add special styling or append some icons to certain elements in the DOM tree view of the Firefox DevTools Inspector?
Whenever "walker" is mentioned in the devtools code, it usually refers to the WalkerActor class in toolkit/devtools/server/actors/inspector.js.
Actors are javascript classes that are specifically made to get information from the currently inspected page and context or manipulate them.
The UI part of the tools you see as a user don't do that directly. Indeed, the devtools use a client-server protocol to communicate between the toolbox (that hosts all of the panels you use) and the actors that run as part of the page being inspected. This is what allows to use the tools to inspect remote devices.
When it comes to the WalkerActor in particular, its role is to traverse the DOM tree and give information about nodes to the inspector-panel so that it can be displayed in the tools.
What you see when you open the devtools inspector on a page is a part of the DOM tree (a part only because it's not entirely expanded and collapsed nodes haven't been retrieved yet) that has been retrieved by the WalkerActor and sent (via the protocol) to the inspector panel.
The actual UI rendering of the panel is done on the client-side (which means, the toolbox side, in comparison with the actors/page side), in browser/devtools/markupview/markup-view.js
In this file, MarkupView and MarkupContainer classes in particular are responsible for displaying nodes. They're not specifically part of the Addons API, but it should be relatively easy to get hold of them since privileged code has access to the gDevTools global variable:
Cu.import("resource://gre/modules/devtools/Loader.jsm");
let target = devtools.TargetFactory.forTab(gBrowser.selectedTab);
let toolbox = gDevTools.getToolbox(target);
let inspectorPanel = toolbox.getPanel("inspector");
inspector.markup // Returns the instance of MarkupView that is currently loaded in the inspector
Is it possible to change the JavaScript alert title in a UIWebview in iPhone?
Basically you cannot change the title, but recently I have found a way to show an alert dialog with no title.
var iframe = document.createElement("IFRAME");
iframe.setAttribute("src", 'data:text/plain,');
document.documentElement.appendChild(iframe);
window.frames[0].window.alert('hello');
iframe.parentNode.removeChild(iframe);
I present three separate solutions to this problem. The best solution for production code is the one described by #Martin H. My only addition to this is a concrete example showing how to implement it.
My other solutions depend on undocumented behaviors of UIWebView, but don't require any changes to the content/JS.
Solution 1: Here is a concrete example demonstrating the technique put forth by #Martin H. This is likely the best solution as it does not rely on UIWebView / UIAlertView undocumented behaviors.
#interface TSViewController () <UIWebViewDelegate>
#end
#implementation TSViewController
- (UIWebView*) webView
{
return (UIWebView*) self.view;
}
- (void) loadView
{
UIWebView* wv = [[UIWebView alloc] initWithFrame: CGRectMake(0, 0, 320, 480)];
wv.delegate = self;
wv.scalesPageToFit = YES;
self.view = wv;
}
- (void) viewDidLoad
{
[super viewDidLoad];
[self.webView loadRequest: [NSURLRequest requestWithURL: [NSURL URLWithString: #"http://www.craigslist.org"]]];
}
- (void) webViewDidFinishLoad: (UIWebView *) webView
{
// inject some js to re-map window.alert()
// ideally just do this in the html/js itself if you have control of that.
NSString* js = #"window.alert = function(message) { window.location = \"http://action/alert?message=\" + message; }";
[webView stringByEvaluatingJavaScriptFromString: js];
// trigger an alert. for demonstration only:
[webView stringByEvaluatingJavaScriptFromString: #"alert('hello, world');" ];
}
- (BOOL) webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
NSURL* url = request.URL;
// look for our custom action to come through:
if ( [url.host isEqualToString: #"action"] && [url.path isEqualToString: #"/alert"] )
{
// parse out the message
NSString* message = [[[[url query] componentsSeparatedByString: #"="] lastObject] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
// show our alert
UIAlertView* av = [[UIAlertView alloc] initWithTitle: #"My Custom Title"
message: message
delegate: nil
cancelButtonTitle: #"OK"
otherButtonTitles: nil];
[av show];
return NO;
}
return YES;
}
Solution 2: First, let me say that I would never personally use the following solution in production code. The best way to achieve this functionality is to do what #Martin H suggests in his answer, or possibly what #twk suggests if an empty title is actually what is desired. If you don't have control over the web content itself, perhaps you could inject #Martin H's code after the content has been loaded.
That said, this is otherwise achievable if we make some assumptions. First, that the Javascript alert() method indeed maps to a real UIAlertView. (In fact it does!) Second, that we can come up with some mechanism to discern an alert()-sourced UIAlertView from other application-sourced UIAlertViews. (We can!)
My approach is to swizzle the UIAlertView. I know - swizzling sucks and has all sorts of drawbacks. I don't swizzle in production apps if I can help it. But for this science project, we're going to swizzle the UIAlertView setDelegate: method.
What I found is that 1) the UIWebView will construct an UIAlertView to display the javascript alert, and 2) the UIAlertView title is set before the UIAlertView delegate is set. By swizzling UIAlertView setDelegate: with my own method I can accomplish two things: 1) I can determine that the UIAlertView is being commissioned on behalf of a UIWebView (just inspect the delegate...) and 2) I have opportunity to re-set the title before the alertview is shown.
You might ask "Why not just swizzle UIAlertview -show method?" That would be great, but in my experimenting I found that the UIWebView never invoked show. It must be calling some other internal method, and I didn't investigate further.
My solution implements a category on UIAlertView, which adds a couple of class methods. Basically you register a UIWebView with these methods, and provide a replacement title to be used. Alternatively you can provide a callback block that returns a title when invoked.
I used the iOS6 NSMapTable class to keep a set of UIWebView-to-Title mappings, where the UIWebView is a weak key. This way I don't ever have to unregister my UIWebView and everything gets cleaned up nicely. Thus, this current implementation is iOS6-only.
Here's the code, shown in-use in a basic view controller:
#import <objc/runtime.h>
typedef NSString*(^TSAlertTitleBlock)(UIWebView* webView, NSString* defaultTitle );
#interface UIAlertView (TS)
#end
#implementation UIAlertView (TS)
NSMapTable* g_webViewMapTable;
+ (void) registerWebView: (UIWebView*) webView alertTitleStringOrBlock: (id) stringOrBlock
{
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
g_webViewMapTable = [NSMapTable weakToStrongObjectsMapTable];
// $wizzle
Method originalMethod = class_getInstanceMethod(self, #selector(setDelegate:));
Method overrideMethod = class_getInstanceMethod(self, #selector(setDelegate_ts:));
method_exchangeImplementations(originalMethod, overrideMethod);
});
[g_webViewMapTable setObject: [stringOrBlock copy] forKey: webView];
}
+ (void) registerWebView: (UIWebView*) webView alertTitle: (NSString*) title
{
[self registerWebView: webView alertTitleStringOrBlock: title];
}
+ (void) registerWebView: (UIWebView*) webView alertTitleBlock: (TSAlertTitleBlock) alertTitleBlock
{
[self registerWebView: webView alertTitleStringOrBlock: alertTitleBlock];
}
- (void) setDelegate_ts: (id) delegate
{
// call the original implementation
[self setDelegate_ts: delegate];
// oooh - is a UIWebView asking for this UIAlertView????
if ( [delegate isKindOfClass: [UIWebView class]] )
{
// see if we've registered a title/title-block
for ( UIWebView* wv in g_webViewMapTable.keyEnumerator )
{
if ( wv != delegate)
continue;
id stringOrBlock = [g_webViewMapTable objectForKey: wv];
if ( [stringOrBlock isKindOfClass: NSClassFromString( #"NSBlock" )] )
{
stringOrBlock = ((TSAlertTitleBlock)stringOrBlock)( wv, self.title );
}
NSParameterAssert( [stringOrBlock isKindOfClass: [NSString class]] );
[self setTitle: stringOrBlock];
break;
}
}
}
#end
#interface TSViewController () <UIWebViewDelegate>
#end
#implementation TSViewController
- (UIWebView*) webView
{
return (UIWebView*) self.view;
}
- (void) loadView
{
UIWebView* wv = [[UIWebView alloc] initWithFrame: CGRectMake(0, 0, 320, 480)];
wv.delegate = self;
wv.scalesPageToFit = YES;
self.view = wv;
}
- (void) viewDidLoad
{
[super viewDidLoad];
// method 1: bind a title to a webview:
[UIAlertView registerWebView: self.webView alertTitle: nil];
/*
// method 2: return a title each time it's needed:
[UIAlertView registerWebView: self.webView
alertTitleBlock: ^NSString *(UIWebView *webView, NSString* defaultTitle) {
return #"Custom Title";
}];
*/
[self.webView loadRequest: [NSURLRequest requestWithURL: [NSURL URLWithString: #"http://www.craigslist.org"]]];
}
- (void) webViewDidFinishLoad: (UIWebView *) webView
{
// trigger an alert
[webView stringByEvaluatingJavaScriptFromString: #"alert('hello, world');" ];
}
#end
Solution 3: Upon reflection, here's a simpler technique than I initially described in Solution 2. It still depends on the undocumented fact that the javascript alert is implemented using a UIAlertView that has its delegate set to the sourcing UIWebView. For this solution, simply subclass UIWebView and implement your own delegate method for UIAlertView willPresentAlertView:, and when it is called, reset the title to whatever you wish.
#interface TSWebView : UIWebView
#end
#implementation TSWebView
- (void) willPresentAlertView:(UIAlertView *)alertView
{
if ( [self.superclass instancesRespondToSelector: #selector( willPresentAlertView:) ])
{
[super performSelector: #selector( willPresentAlertView:) withObject: alertView];
}
alertView.title = #"My Custom Title";
}
#end
#interface TSViewController () <UIWebViewDelegate>
#end
#implementation TSViewController
- (UIWebView*) webView
{
return (UIWebView*) self.view;
}
- (void) loadView
{
UIWebView* wv = [[TSWebView alloc] initWithFrame: CGRectMake(0, 0, 320, 480)];
wv.delegate = self;
wv.scalesPageToFit = YES;
self.view = wv;
}
- (void) viewDidLoad
{
[super viewDidLoad];
[self.webView loadRequest: [NSURLRequest requestWithURL: [NSURL URLWithString: #"http://www.craigslist.org"]]];
}
- (void) webViewDidFinishLoad: (UIWebView *) webView
{
// trigger an alert
[webView stringByEvaluatingJavaScriptFromString: #"alert('hello, world');" ];
}
#end
No you can't do this in a Javascript alert.
But if the Javascript is yours then instead of calling the alert you could instead call a function that calls Objective C and invoke an iOS native alert.
If the Javascript isn't yours then using UIWebView you can inject some Javascript to override the default behaviour and change it to call an iOS native alert i.e. something like this
window.alert = function(message) {
window.location = "myScheme://" + message"
};
Then look for myScheme and extract message in UIWebView's shouldStartLoadWithRequest
Here's the standard method for invoking Objective-C from Javascript
How to call Objective-C from Javascript?
For what it's worth, Phonegap/Cordova offers a navigator.notification.alert function. It allows specifying a custom title.
Just make a class for your UIWebView and make willPresentAlertView (alertView: UIAlertView) function in it. After that set alertView.title = "your fav title" and it is done.
import UIKit
class webviewClass: UIWebView {
func willPresentAlertView(alertView: UIAlertView) {
alertView.title = "my custum title"
}
}
After that when ever an alert or confirm and... shown, your custom title will shown.
Going off of what #twk wrote, I simply overwrite the alert function. Works great on ios7.
function alert(words){
var iframe = document.createElement("IFRAME");
iframe.setAttribute("src", 'data:text/plain,');
document.documentElement.appendChild(iframe);
window.frames[0].window.alert(words);
iframe.parentNode.removeChild(iframe);
}
Use cordova-plugin-dialogs. It allows to create native dialogs.
Below code will create native alert:
navigator.notification.alert(message, alertCallback, [title], [buttonName])
I have a view controller with a UIWebView controller. I'm trying to get the javascript inside the html content of the web view to pass some information to my objective c code. I came across a number of examples online that set window.location in a javascript function and then catch the event generated by setting the view controller to be the web view's delegate and catching it in the shouldStartLoadWithRequest function. Unfortunately I can't get it to work because for me shouldStartLoadWithRequest is never called even though I'm setting the web view's delegate.
My code is as follows:
The interface:
#interface StoryTextViewController : UIViewController <UIWebViewDelegate>
{
IBOutlet UIWebView *storyWebView;
NSString *information;
}
#property (nonatomic, retain) IBOutlet UIWebView *storyWebView;
#property (nonatomic, retain) NSString *information;
#end
In the interface, the *information variable is set by the previous view that calls StoryTextViewController.
The implementation:
#import "StoryTextViewController.h"
#implementation StoryTextViewController
#synthesize storyWebView;
#synthesize information;
- (NSString *) contructHTMLText
{
NSString *HTMLText = #"";
NSArray *words = [information componentsSeparatedByString:#" "];
NSString *header =
#"<html>\n"
"<head>\n"
"<script type=\"text/javascript\">\n"
"function marktext(theSpanID)\n"
"{\n"
" var theSpan=document.getElementById(theSpanID);\n"
" if (theSpan.className == \"noHilite\")\n"
" {\n"
" theSpan.className = \"hilite\";\n"
" window.location = \"true\";\n"
" }\n"
" else\n"
" {\n"
" theSpan.className = \"noHilite\";\n"
" window.location = \"false\";\n"
" }\n"
"}\n"
"</script>\n"
"<style type=\"text/css\">\n"
".hilite\n"
"{\n"
" background-color:red;\n"
" color:white;\n"
" font: bold 60px arial,sans-serif\n"
"}\n"
".noHilite\n"
"{\n"
" background-color:white;\n"
" color:black;\n"
" font: 60px arial,sans-serif\n"
"}\n"
"</style>\n"
"</head>\n"
"<body>\n"
"<div class=\"storyText\">\n";
NSString *tailer =
#"</div>\n"
"</body>\n"
"</html>\n";
HTMLText = [HTMLText stringByAppendingString:header];
for (NSInteger i = 0; i < [words count]; i ++)
{
NSString *tag = [NSString stringWithFormat:#" <span id=\"mytext%d\" class=\"noHilite\" onclick=\"marktext(\'mytext%d\')\">%#</span> \n", i, i, (NSString *)[words objectAtIndex:i]];
HTMLText = [HTMLText stringByAppendingString:tag];
}
HTMLText = [HTMLText stringByAppendingString:tailer];
NSLog(HTMLText);
return HTMLText;
}
// The designated initializer. Override to perform setup that is required before the view is loaded.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
storyWebView.delegate = self;
}
return self;
}
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad
{
[super viewDidLoad];
NSString *HTMLData = [self contructHTMLText];
[storyWebView loadHTMLString:HTMLData baseURL:[NSURL URLWithString: #""]];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning]; // Releases the view if it doesn't have a superview
// Release anything that's not essential, such as cached data
}
- (void)dealloc {
[super dealloc];
}
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
// handle event here
return true;
}
#end
Whats happening is that basically, the constructHTML function takes the text inside the *information variable and wraps every word in the text with some html and javascript such that whenever a word is clicked, a css high-lighting is applied on it. What I want to do is to count the number of high-lighted words. I do this by trying to pass something in the function thats called whenever a word is clicked but like i said, the shouldStartLoadWithRequest method thats supposed to be fired is never executed.
I've seen a lot of people do this sort of thing but I cant seem to figure out why its not running for me
You can put breakpoint on setting delegate
if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
storyWebView.delegate = self;
}
I'm pretty sure storyWebView is nil on that moment.
You can fix it in this manner:
- (void)viewDidLoad
{
[super viewDidLoad];
NSString *HTMLData = [self contructHTMLText];
// empty statement
// the trick is that if the view is not loaded from the .nib yet
// it will be loaded and all connections established
if (self.view);
// here is setting delegate
storyWebView.delegate = self;
[storyWebView loadHTMLString:HTMLData baseURL:[NSURL URLWithString: #""]];
}
You should set the delegate in viewDidLoad, not in initWithNibName:bundle:. Alternatively, open up your nib file and control-drag from the web view to your File's Owner, and choose "delegate" from the drop down.
Shouldn't window.location be the value of the target URL you are going to? In your marktext function you're setting it to true or false. shouldStartLoadWithRequest gets called only when a URL request has been received and is about to go somewhere. Not sure setting the location to a boolean is enough to trigger a navigation event. You can set it to a magic URL then return FALSE from the shouldStartLoadWithRequest routine if it's asking to navigate to that specific magic URL and prevent it from actually going somewhere. Valid URLs can then be allowed to go through.
Also might want to take a look at the response to this SO question. There may be some timing issues with window.location.
I also see this problem, because I have set the
articleWeb.userInteractionEnabled = NO;`
you'd better check your code, set
articleWeb.userInteractionEnabled = YES;`