Change JavaScript alert dialog title in iOS - javascript

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])

Related

How to force Android-WebView to Redraw/Re-Render immediately?

Basically the JavascriptInterface receive a Click event from WebView, then I need to change an HTML element multiple times, the problem is the WebView show only the last change, that's mean the rendering is not immediate.
Question: How to make webview.loadUrl("javascript:updateProgress(20);"); take effect and change WebView content immediately?
- - - - - - - - - - - - - - - - -
Old question:
I have a HTML progress-bar in my WebView, I can simply update the progress-bar value by running webview.loadUrl("javascript:updateProgress(20);"); this work fine from onCreate().
// JavaScript in WebView
function updateProgress(percentage){
document.getElementById('progressBar').style.width = percentage + '%';
}
Now, I have a class that send binary data to an connected BLE device, I toke the example from Google BluetoothLeGatt, and I added a method to write to an characteristic (send data) in BluetoothLeService.java.
public void WriteCharacteristic(BluetoothGattCharacteristic characteristic, byte[] data, MainActivity mainactivity){
byte[] data_twenty_byte = new byte [20];
int progress_count = 0;
while(get_next_twenty_byte(data, data_twenty_byte)){
characteristic.setValue(data_twenty_byte);
mBluetoothGatt.writeCharacteristic(characteristic);
progress_count++;
mainactivity.webview.loadUrl("javascript:updateProgress(" + progress_count + ");");
}
}
The problem is the WebView won't be updated (Redraw/Re-Render) while WriteCharacteristic() is running, the WebView Redraw/Re-Render only after WriteCharacteristic() finish, mean at progress-bar 100%.
Note: I already tried runOnUiThread(new Runnable() {});
My Question is, How to force mainactivity.webview to Redraw/Re-Render immediately ?
Thank you,
As noted in my comment, pushing the long-running process to a background thread, then running the webview update on the ui thread should do what you are looking to achieve. Here's a quick example that I threw together:
package com.example.myapplication
import android.annotation.SuppressLint
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.webkit.JavascriptInterface
import android.webkit.WebView
import kotlin.concurrent.thread
class MainActivity : AppCompatActivity() {
lateinit var webView: WebView
#SuppressLint("SetJavaScriptEnabled")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
webView = WebView(this)
webView.settings.javaScriptEnabled = true
webView.addJavascriptInterface(this, "app")
setContentView(webView)
val html =
"""
<html>
<head>
<script type='text/javascript'>
function updateProgress(progress) {
let el = document.getElementById('progress');
el.innerText = progress;
}
</script>
</head>
<body>
<p>Value: <span id='progress'>0</span></p>
<button onclick='app.startUpdates();'>Start Update</button>
</body>
</html>
""".trimIndent()
webView.loadData(html, "text/html", "UTF-8")
}
#JavascriptInterface
fun startUpdates() {
doSomething()
}
private fun doSomething() {
thread {
for (i in 1..100) {
runOnUiThread { webView.evaluateJavascript("updateProgress($i);", null) }
Thread.sleep(10)
}
}
}
}

Expose native methods in JavaScript in WKWebView

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

How to scroll programmatically to a to a line in UIWebView?

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.

iPhone WebApp Question

I have this code-
/**
Save the web view as a screenshot. Currently only supports saving to
the photo library.
/
- (void)saveScreenshot:(NSArray)arguments withDict:(NSDictionary*)options
{
CGRect screenRect = [[UIScreen mainScreen] bounds];
CGRect imageRect = CGRectMake(0, 0, CGRectGetWidth(screenRect),
CGRectGetHeight(screenRect));
UIGraphicsBeginImageContext(imageRect.size);
[webView.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
UIImageWriteToSavedPhotosAlbum(viewImage, self, nil, nil);
UIAlertView *alert= [[UIAlertView alloc] initWithTitle:nil
message:#"Image Saved" delegate:self cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
[alert release];
}
This is for saving whatever you drew in my app. How would I add the button for this in the HTML code. How do i call from it?
So you are trying to send an event from html to a UIWebView?
The easiest way is to use a private scheme. In the html:
Take Picture
In the UIWebView delegate:
-(BOOL) webView:(UIWebView *)inWeb shouldStartLoadWithRequest:(NSURLRequest *)inRequest navigationType:(UIWebViewNavigationType)inType {
NSString *string = [[[inRequest URL] absoluteString] lowercaseString];
if ( [string isEqualToString:#"myscheme:save_picture"] ) {
[self savePicture];
return NO;
}
return YES;
}
You can look at PhoneGap for a more robust usage of this mechanism.

shouldStartLoadWithRequest is not called in my iPhone App

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;`

Categories