What is WKErrorDomain error 4 from WKWebView - javascript

fatal error: LPWebView encounters an error: Error Domain=WKErrorDomain Code=4
"A JavaScript exception occurred" UserInfo=0x79d9c700
{NSLocalizedDescription=A JavaScript exception occurred}
I encountered this error when I tried to evaluate a JavaScript function with WKWebView.
I used loadHTMLString to load a template to the webview.
let bundle = NSBundle.mainBundle()
if let editorURL = bundle.URLForResource(self.kTemplateName,
withExtension: "html") {
var error : NSError?
//get html string from editor.html
if let htmlString = String(contentsOfURL: editorURL, encoding: NSUTF8StringEncoding, error: &error){
if error != nil {
assertionFailure("error encountered reading html string for \(error)")
} else {
self.loadHTMLString(htmlString, baseURL: bundle.bundleURL)
}
}
} else {
assertionFailure("LPWebView template not found")
}
I wonder what this error code means and how to solve it?
Thank you very much!

So if we dig into the headers:
/*! #constant WKErrorDomain Indicates a WebKit error. */
#availability(iOS, introduced=8.0)
let WKErrorDomain: String
/*! #enum WKErrorCode
#abstract Constants used by NSError to indicate errors in the WebKit domain.
#constant WKErrorUnkcnown Indicates that an unknown error occurred.
#constant WKErrorWebContentProcessTerminated Indicates that the Web Content process was terminated.
#constant WKErrorWebViewInvalidated Indicates that the WKWebView was invalidated.
#constant WKErrorJavaScriptExceptionOccurred Indicates that a JavaScript exception occurred.
*/
#availability(iOS, introduced=8.0)
enum WKErrorCode : Int {
case Unknown
case WebContentProcessTerminated
case WebViewInvalidated
case JavaScriptExceptionOccurred
}
Error code 4 would corresponds to JavaScriptExceptionOccurred, or WKErrorJavaScriptExceptionOccurred.
In other words, the JavaScript function causes some error.
Probably not more here that you couldn't guess already. For resolution, I would suggest using the developer features of a web browser such as Safari, loading the HTML and debugging.
In fact, as explained in the WWDC 2014 video, "Introducing the Modern WebKit API", your desktop Safari browser can "inspect the WKWebView using the Safari web inspector, including any user scripts that you've injected."
To use this, while the WKWebView is loaded in memory in your running app on the iOS simulator, open the desktop Safari browser and access Develop on the top menu bar then iOS Simulator. That will show a drop down of the web view's document objects.
For more info on debugging JavaScript, take a look at Web Inspector: Understanding Stack Traces

Related

How to send data from WKWebview to HTML file using evaluateJavaScript | iOS | Objective-C

I need to pass certain values to my HTML from WKWebview.
Here is my code snipped of what I've tried yet.
[self.webView evaluateJavaScript:#"document.getElementById('popo_data').innerHTML = feed,OMG,BTC;" completionHandler:^(NSString *result, NSError *error) {
if(error != nil) {
NSLog(#"######## SomeFunction Error: %#",error);
return;
}
NSLog(#"######## SomeFunction Success");
}];
That does not look like well formed JavaScript, because quotes are missing around the string you're assigning to the #popo_data element. I suppose you're getting a syntax error here.
Try the following:
document.getElementById('popo_data').innerHTML = "feed,OMG,BTC"
If this does not work, you can debug your webview with Safari by connecting the debugger to your device or simulator. Safari Preferences > check "Show Develop menu in menu bar."

What is causing this link to error saying "is not a valid virtual path"?

I have some code that works locally but when I put it up live, it causes an error. Not just an error, but the page doesn't load and I get a huge error page that states:
'/Clients/CMCDFMIS/gateway.htm?p=Dallas' is not a valid virtual path.
Description: An unhandled exception occurred during the execution of
the current web request. Please review the stack trace for more
information about the error and where it originated in the code.
Exception Details: System.Web.HttpException:
'/Clients/CMCDFMIS/gateway.htm?p=Dallas' is not a valid virtual path.
Source Error:
An unhandled exception was generated during the execution of the
current web request. Information regarding the origin and location of
the exception can be identified using the exception stack trace below.
Stack Trace:
[HttpException (0x80004005): '/Clients/CMCDFMIS/gateway.htm?p=Dallas'
is not a valid virtual path.] System.Web.VirtualPath.Create(String
virtualPath, VirtualPathOptions options) +8877083
System.Web.VirtualPath.Create(String virtualPath) +9
System.Web.UI.PageParser.GetCompiledPageInstance(String virtualPath,
String inputFile, HttpContext context) +163
AtgHttpHandler.AtgHttpHandler.ProcessRequest(HttpContext context) +804
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
+181 System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +75
Version Information: Microsoft .NET Framework Version:2.0.50727.4062;
ASP.NET Version:2.0.50727.5692
HTML:
<a href="../gateway.htm?p=Dallas">
What I am doing with it is in JavaScript:
urlExtract = location.search
foundExtract = urlExtract.split("=")[1];
if(foundExtract == "Dallas"){
//do something
}
else if(foundExtract == "Legacy"){
//do something
}
I don't think it is really getting to the JavaScript though. I have used this urlextract code on another site years and years ago so I am not sure why in this case it is giving me problems?

Parallel.js have problems with Blob in IE

I need to execute functions in "parallel" and I use parallel.js:
var p = new Parallel(items);
var fn1 = function (item) {
doSomething(item);
};
p.map(fn1).then(function () {
otherFunction();
});
But IE shows the following error:
[Q] Unhandled rejection reasons (should be empty): (no stack) SecurityError
HTML7007: One or more blob URLs were revoked by closing the blob
for which they were created. These URLs will no longer resolve as
the data backing the URL has been freed.
How to fix this error?
I had review parallel.js page in IE and all examples work fine.
I use Durandal, Breeze and Knockout.
In Firefox shows the following error:
[Q] Unhandled rejection reasons (should be empty):
["(no stack) [Exception..... location: "<unknown>"]"]
and in Google Chrome no shows error, but parallel.js no work.
In case you're still having trouble with this, to make Parallel.js work in Internet Explorer you have to include the evalPath option, as mentioned on the website:
evalPath (optional): This is the path to the file eval.js. This is
required when running in node, and required when requiring files in
browser environments (to work around cross-domain restrictions for web
workers in IE 10).
This also applies to IE 11.
So your code will become:
var p = new Parallel(items, {evalPath: [PATH_TO_EVAL_JS]});
Where [PATH_TO_EVAL_JS] points to eval.js.

How to debug the silk browser on the Kindle Fire?

I am experiencing some different javascript behavior when running my site on Kindle Fire than through Chrome. In order to debug this I need access to something like the Chrome Developer Tool or Firebug. Any suggestions?
In the same boat here... was hoping adb logcat would help, but javascript console messages don't seem to appear there. Perhaps there's something that needs to be set on the device to direct console logs to logcat?
edit: found a decent solution: http://jsconsole.com -- allows you to set up a remote debug/logging console. Pretty simple (console logging only, so you'll need to dump a lot of into into the logs)... but it works well. Helped me track down the source of my issues, at least!
how-to: http://jsconsole.com/remote-debugging.html
I took a different approach and created a wrapper native app that pop up a dialog for JavaScript.
My wrapper code is rather large, so I took a snippet of the relavant parts. It actually works and will display ANY javascript error.
// registers the debugger to catch errors
WebView engine = (WebView) findViewById(R.id.web_engine);
engine.setWebChromeClient(new DebugClient(this));
// the class that manages the errors
private class DebugClient extends WebChromeClient {
Activity activity;
public DebugClient(Activity activity) {
this.activity = activity;
}
#Override
public boolean onConsoleMessage(ConsoleMessage consoleMessage) {
if (consoleMessage.messageLevel() == MessageLevel.ERROR
|| consoleMessage.messageLevel() == MessageLevel.WARNING) {
String title="Javascript error on line "
+ String.valueOf(consoleMessage.lineNumber())
+ " of " + consoleMessage.sourceId();
AlertBox alertBox=new AlertBox(activity, (ActionListener)null, title, consoleMessage.message(), "OK");
alertBox.show();
alertBoxes.add(alertBox);
}
return true;
}
}
To compile this, you'll need to install the Android SDK on your computer, and probably a Java IDE (Eclipse?) with ADT. Then you just do: create new project, add a WebView component into your layout/main.xml, and paste the code. Compile and install on your Kindle Fire.

Detecting JavaScript errors in a UIWebView [duplicate]

I need to have my iPhone Objective-C code catch Javascript errors in a UIWebView. That includes uncaught exceptions, syntax errors when loading files, undefined variable references, etc.
This is for a development environment, so it doesn't need to be SDK-kosher. In fact, it only really needs to work on the simulator.
I've already found used some of the hidden WebKit tricks to e.g. expose Obj-C objects to JS and to intercept alert popups, but this one is still eluding me.
[NOTE: after posting this I did find one way using a debugging delegate. Is there a way with lower overhead, using the error console / web inspector?]
I have now found one way using the script debugger hooks in WebView (note, NOT UIWebView). I first had to subclass UIWebView and add a method like this:
- (void)webView:(id)webView windowScriptObjectAvailable:(id)newWindowScriptObject {
// save these goodies
windowScriptObject = newWindowScriptObject;
privateWebView = webView;
if (scriptDebuggingEnabled) {
[webView setScriptDebugDelegate:[[YourScriptDebugDelegate alloc] init]];
}
}
Next you should create a YourScriptDebugDelegate class that contains methods like these:
// in YourScriptDebugDelegate
- (void)webView:(WebView *)webView didParseSource:(NSString *)source
baseLineNumber:(unsigned)lineNumber
fromURL:(NSURL *)url
sourceId:(int)sid
forWebFrame:(WebFrame *)webFrame
{
NSLog(#"NSDD: called didParseSource: sid=%d, url=%#", sid, url);
}
// some source failed to parse
- (void)webView:(WebView *)webView failedToParseSource:(NSString *)source
baseLineNumber:(unsigned)lineNumber
fromURL:(NSURL *)url
withError:(NSError *)error
forWebFrame:(WebFrame *)webFrame
{
NSLog(#"NSDD: called failedToParseSource: url=%# line=%d error=%#\nsource=%#", url, lineNumber, error, source);
}
- (void)webView:(WebView *)webView exceptionWasRaised:(WebScriptCallFrame *)frame
sourceId:(int)sid
line:(int)lineno
forWebFrame:(WebFrame *)webFrame
{
NSLog(#"NSDD: exception: sid=%d line=%d function=%#, caller=%#, exception=%#",
sid, lineno, [frame functionName], [frame caller], [frame exception]);
}
There is probably a large runtime impact for this, as the debug delegate can also supply methods to be called for entering and exiting a stack frame, and for executing each line of code.
See http://www.koders.com/noncode/fid7DE7ECEB052C3531743728D41A233A951C79E0AE.aspx for the Objective-C++ definition of WebScriptDebugDelegate.
Those other methods:
// just entered a stack frame (i.e. called a function, or started global scope)
- (void)webView:(WebView *)webView didEnterCallFrame:(WebScriptCallFrame *)frame
sourceId:(int)sid
line:(int)lineno
forWebFrame:(WebFrame *)webFrame;
// about to execute some code
- (void)webView:(WebView *)webView willExecuteStatement:(WebScriptCallFrame *)frame
sourceId:(int)sid
line:(int)lineno
forWebFrame:(WebFrame *)webFrame;
// about to leave a stack frame (i.e. return from a function)
- (void)webView:(WebView *)webView willLeaveCallFrame:(WebScriptCallFrame *)frame
sourceId:(int)sid
line:(int)lineno
forWebFrame:(WebFrame *)webFrame;
Note that this is all hidden away in a private framework, so don't try to put this in code you submit to the App Store, and be prepared for some hackery to get it to work.
I created a nice little drop-in category that you can add to your project...
It is based on Robert Sanders solution. Kudos.
You can dowload it here:
UIWebView+Debug
This should make it a lot easier to debug you UIWebView :)
I used the great solution proposed from Robert Sanders: How can my iPhone Objective-C code get notified of Javascript errors in a UIWebView?
That hook for webkit works fine also on iPhone. Instead of standard UIWebView I allocated derived MyUIWebView. I needed also to define hidden classes inside MyWebScriptObjectDelegate.h:
#class WebView;
#class WebFrame;
#class WebScriptCallFrame;
Within the ios sdk 4.1 the function:
- (void)webView:(id)webView windowScriptObjectAvailable:(id)newWindowScriptObject
is deprecated and instead of it I used the function:
- (void)webView:(id)sender didClearWindowObject:(id)windowObject forFrame:(WebFrame*)frame
Also, I get some annoying warnings like "NSObject may not respond -windowScriptObject" because the class interface is hidden. I ignore them and it works nice.
One way that works during development if you have Safari v 6+ (I'm uncertain what iOS version you need) is to use the Safari development tools and hook into the UIWebView through it.
In Safari: Enable the Develop Menu (Preferences > Advanced > Show Develop menu in menu bar)
Plug your phone into the computer via the cable.
List item
Load up the app (either through xcode or just launch it) and go to the screen you want to debug.
Back in Safari, open the Develop menu, look for the name of your device in that menu (mine is called iPhone 5), should be right under User Agent.
Select it and you should see a drop down of the web views currently visible in your app.
If you have more than one webview on the screen you can try to tell them apart by rolling over the name of the app in the develop menu. The corresponding UIWebView will turn blue.
Select the name of the app, the develop window opens and you can inspect the console. You can even issue JS commands through it.
Straight Forward Way: Put this code on top of your controller/view that is using the UIWebView
#ifdef DEBUG
#interface DebugWebDelegate : NSObject
#end
#implementation DebugWebDelegate
#class WebView;
#class WebScriptCallFrame;
#class WebFrame;
- (void)webView:(WebView *)webView exceptionWasRaised:(WebScriptCallFrame *)frame
sourceId:(int)sid
line:(int)lineno
forWebFrame:(WebFrame *)webFrame
{
NSLog(#"NSDD: exception: sid=%d line=%d function=%#, caller=%#, exception=%#",
sid, lineno, [frame functionName], [frame caller], [frame exception]);
}
#end
#interface DebugWebView : UIWebView
id windowScriptObject;
id privateWebView;
#end
#implementation DebugWebView
- (void)webView:(id)sender didClearWindowObject:(id)windowObject forFrame:(WebFrame*)frame
{
[sender setScriptDebugDelegate:[[DebugWebDelegate alloc] init]];
}
#end
#endif
And then instantiate it like this:
#ifdef DEBUG
myWebview = [[DebugWebView alloc] initWithFrame:frame];
#else
myWebview = [[UIWebView alloc] initWithFrame:frame];
#endif
Using #ifdef DEBUG ensures that it doesn't go in the release build, but I would also recommend commenting it out when you're not using it since it has a performance impact. Credit goes to Robert Sanders and Prcela for the original code
Also if using ARC you may need to add "-fno-objc-arc" to prevent some build errors.
I have created an SDK kosher error reporter that includes:
The error message
The name of the file the error happens in
The line number the error happens on
The JavaScript callstack including parameters passed
It is part of the QuickConnectiPhone framework available from the sourceForge project
There is even an example application that shows how to send an error message to the Xcode terminal.
All you need to do is to surround your JavaScript code, including function definitions, etc. with try catch. It should look like this.
try{
//put your code here
}
catch(err){
logError(err);
}
It doesn't work really well with compilation errors but works with all others. Even anonymous functions.
The development blog is here
is here and includes links to the wiki, sourceForge, the google group, and twitter. Maybe this would help you out.
I have done this in firmware 1.x but not 2.x.
Here is the code I used in 1.x, it should at least help you on your way.
// Dismiss Javascript alerts and telephone confirms
/*- (void)alertSheet:(UIAlertSheet*)sheet buttonClicked:(int)button
{
if (button == 1)
{
[sheet setContext: nil];
}
[sheet dismiss];
}*/
// Javascript errors and logs
- (void) webView: (WebView*)webView addMessageToConsole: (NSDictionary*)dictionary
{
NSLog(#"Javascript log: %#", dictionary);
}
// Javascript alerts
- (void) webView: (WebView*)webView runJavaScriptAlertPanelWithMessage: (NSString*) message initiatedByFrame: (WebFrame*) frame
{
NSLog(#"Javascript Alert: %#", message);
UIAlertSheet *alertSheet = [[UIAlertSheet alloc] init];
[alertSheet setTitle: #"Javascript Alert"];
[alertSheet addButtonWithTitle: #"OK"];
[alertSheet setBodyText:message];
[alertSheet setDelegate: self];
[alertSheet setContext: self];
[alertSheet popupAlertAnimated:YES];
}
See exception handling in iOS7:
http://www.bignerdranch.com/blog/javascriptcore-example/
[context setExceptionHandler:^(JSContext *context, JSValue *value) {
NSLog(#"%#", value);
}];
First setup WebViewJavascriptBridge ,
then override console.error function.
In javascript
window.originConsoleError = console.error;
console.error = (msg) => {
window.originConsoleError(msg);
bridge.callHandler("sendConsoleLogToNative", {
action:action,
message:message
}, null)
};
In Objective-C
[self.bridge registerHandler:#"sendConsoleLogToNative" handler:^(id data, WVJBResponseCallback responseCallback) {
NSString *action = data[#"action"];
NSString *msg = data[#"message"];
if (isStringValid(action)){
if ([#"console.error" isEqualToString:action]){
NSLog(#"JS error :%#",msg);
}
}
}];
A simpler solution for some cases might be to just add Firebug Lite to the Web page.

Categories

Resources