GithubHelp home page GithubHelp logo

oracle / cordova-plugin-wkwebview-file-xhr Goto Github PK

View Code? Open in Web Editor NEW
138.0 25.0 120.0 110 KB

Cordova Plugin for WebView File XHR

License: Universal Permissive License v1.0

Objective-C 17.48% JavaScript 82.23% HTML 0.29%
cordova-plugin cordova oraclejet

cordova-plugin-wkwebview-file-xhr's Introduction

cordova-plugin-wkwebview-file-xhr 3.1.1

About the cordova-plugin-wkwebview-file-xhr

This plugin makes it possible to reap the performance benefits of using the WKWebView in your Cordova app by resolving the following issues:

  • The default behavior of WKWebView is to raise a cross origin exception when loading files from the main bundle using the file protocol - "file://". This plugin works around this shortcoming by loading files via native code if the web view's current location has "file" protocol and the target URL passed to the open method of the XMLHttpRequest is relative. As a security measure, the plugin verifies that the standardized path of the target URL is within the "www" folder of the application's main bundle or in the /Library path of the application data directory.

  • Since the application's starting page is loaded from the device's file system, all XHR requests to remote endpoints are considered cross origin. For such requests, WKWebView specifies "null" as the value of the Origin header, which will be rejected by endpoints that are configured to disallow requests from the null origin. This plugin works around that issue by handling all remote requests at the native layer where the origin header will be excluded.

Installation

Plugin installation requires Cordova 4+ and iOS 9+. It will install the Apache Cordova WKWebView plugin cordova-plugin-wkwebview-engine.

cordova plugin add cordova-plugin-wkwebview-file-xhr

Note : If your cordova-ios version is less than 6.0.0. You need to add following dependency to plugin.xml

<dependency id="cordova-plugin-wkwebview-engine" />

Alternatively you can use this plugin's version 2.1.4

Supported Platforms

  • iOS

Quick Example

// read local resource
var xhr = new XMLHttpRequest();
xhr.addEventListener("loadend", function(evt)
 {
   var data = this.responseText;
   document.getElementById("myregion").innerHTML = data;
 });

xhr.open("GET", "js/views/customers.html");
xhr.send();

// post to remote endpoint
var xhr = new XMLHttpRequest();
xhr.addEventListener("loadend", function(evt)
 {
   var product = this.response;
   document.getElementById("productId").value = product.id;
   document.getElementById("productName").value = product.name;
 });

xhr.open("POST", "https://myremote/endpoint/product");
xhr.responseType = "json";
xhr.setRequestHeader("Content-Type", "application/json");
xhr.setRequestHeader("Accept", "application/json");
xhr.send(JSON.stringify({name: "Product 99"}));

Configuration

The following configuration options modify the default behavior of the plugin. The values are specified in config.xml as preferences:

  • AllowUntrustedCerts: on|off (default: off). If "on", requests routed to the native implementation will accept self signed SSL certificates. This preference should only be enabled for testing purposes.
  • InterceptRemoteRequests: all|secureOnly|none (default: secureOnly). Controls what types of remote XHR requests are intercepted and handled by the plugin. The plugin always intercepts requests with the file:// protocol. By default, the plugin will intercept only secure protocol requests ("https").
  • NativeXHRLogging: none|full (default: none). If "full" the javascript layer will produce logging of the XHR requests sent through the native to the javascript console. Note: natively routed XHR requests will not appear in the web inspector utility when "InterceptRemoteRequests" is "all" or "secureOnly".

Known Issues

The plugin caches cookies at the native layer between requests but it does not attempt to sync cookies between the WKWebView and the native sessions. From the JavaScript context, this means "document.cookie" won't contain any cookies returned from XHR handled at the native layer and the native iOS XHR will not see any cookies returned from remote resources fetched by the browser context, such as images.

Whilst this plugin resolves the main issues preventing the use of the Apache Cordova WKWebView plugin, there are other known issues with that plugin.

See CHANGELOG.

Contributing

This project is not accepting external contributions at this time. For bugs or enhancement requests, please file a GitHub issue unless it’s security related. When filing a bug remember that the better written the bug is, the more likely it is to be fixed. If you think you’ve found a security vulnerability, do not raise a GitHub issue and follow the instructions in our security policy.

Security

Please consult the security guide for our responsible security vulnerability disclosure process

License

Copyright (c) 2018, 2023 Oracle and/or its affiliates The Universal Permissive License (UPL), Version 1.0

cordova-plugin-wkwebview-file-xhr's People

Contributors

anandvnath avatar brunoborges avatar eivindml avatar gvanmat avatar manish2788 avatar spavlusieva avatar velochy avatar vguddant avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

cordova-plugin-wkwebview-file-xhr's Issues

Script in head do not load

I have simple script tag in head

<script src="https://cdn.announcekit.app/widget.js"></script>

When I start app I got message "An error occurred trying to load the resource" in console.

Does anybody know how to fix it?

Thanks!

XMLHttpRequest.onerror is called erroneously if status code >= 400

The onerror callback should only be called on network-level errors; If there is a response then, by definition, there was no network level error. The value of the status code is irrelevant. More discussion is at https://stackoverflow.com/questions/10584318/when-should-xmlhttprequests-onerror-handler-fire

if (payload.response.statusCode === 0 || payload.response.statusCode >= 400)
  reqContext.dispatchProgressEvent("error", respSize);

For the record, angularjs registers an onerror handler that correctly discards any results. So all $http calls that return a statusCode >= 400 now look like network errors.

Shared iOS Folders

This plugin works fine when accessing files within the read-only www application dir as mentioned in the readme.

The plugin cordova-plugin-file (https://cordova.apache.org/docs/en/latest/reference/cordova-plugin-file/) supports file-writing to an application-specific read/write space.

Shouldn't the security check focus on the container base path? Or make the security check configurable?

Example:

Current security check on read-only ww dir: /var/containers/Bundle/Application/9579B5BA-ED95-4D9E-AF6D-3524725791CE/HelloWorld.app/www

Proposed: /var/containers/Bundle/Application/9579B5BA-ED95-4D9E-AF6D-3524725791CE

No 'responseText' property in response object on 403 (forbidden) error

Hi!

I added authentication in my phonegap app. But when I send wrong password, I receive only properties 'status', 'statusText', 'readyState'. But I debugged your code and found that the plugin had 'responseText' property inside. It's very important to me to have 'responseText', because this properti is used to send to the application some messages like 'wrong credentials' or some other.

This object I found when I was debugging:

{
  "_context": {
    "delegate": null,
    "requestHeaders": {
      "content-type": "application/json",
      "accept": "application/json, text/javascript, */*; q=0.01"
    },
    "responseHeaders": {
      "date": "Tue, 31 Oct 2017 16:25:21 GMT",
      "keep-alive": "timeout=65, max=499",
      "content-length": "302",
      "connection": "Keep-Alive",
      "content-type": "application/json; charset=utf-8",
      "server": "Apache/2.4.18 (Ubuntu)"
    },
    "listeners": {},
    "readyState": 4,
    "responseType": "text",
    "withCredentials": true,
    "upload": {
      "_context": {
        "listeners": {}
      }
    },
    "status": 403,
    "method": "GET",
    "url": "https://example.com/auth",
    "async": true,
    "responseURL": "http://example.com/auth",
    "statusText": "forbidden",
    "response": "{\"meta\":{\"errors\":[{\"code\":102,\"message\":\"Invalid password.\"}]}",
    "responseText": "{\"meta\":{\"errors\":[{\"code\":102,\"message\":\"Invalid password.\"}]"
  }
}

This properties I received in jqXHR object:

{"readyState":4,"status":403,"statusText":"forbidden"}

How does it work?

Hello,

I added this plugin to my Cordova project to fix the following issue:

XMLHttpRequest cannot load file:///var/containers/Bundle/Application/51326CDD-4449-480E-908C-2E4CC131F0E1/Example%20app.app/www/app/dist/img/sprite.svg. Cross origin requests are only supported for HTTP.

Even after I added this plugin and build my app again the issue isn't resolved.

Is this plugin intended to fix this kind of issue?

Thank you,

Debugging a result with status -1

I am making a post request and it comes back to the webview as Status: -1.
I would really like to know what is going wrong but I have no clue even where to start. Normally, I would look at safari Resources tab and get the request headers + server response. Any way I can access this info even when this plugin is in place?

cordova 9 and ios 12

I am using angular 7 with the default httpClient but seems that it is not working with sticky cookies, is there any particular config to make cookies sticky?

Screen change orientation bug

Hi there:

When a change the orientation of my device (iPad Mini running iOS 11.2.6) wkwebview doesn't cover the entire height of screen.

That is, when the WKWebView is used, rotating the screen doesn't trigger a resize of the HTML, but it works correctly with UIWebView.

It's possible to "hack" this behavior firing a temporized window.dispatchEvent(new Event('resize'), but I find it clumsy as it involves a Race Condition.

Maybe it has to be with this code in Xcode?:

CGRect screenBounds = [[UIScreen mainScreen] bounds]; self.window = [[UIWindow alloc] initWithFrame:screenBounds]; self.window.autoresizesSubviews = YES;

Any help on this?

2.1.0 release

Hey, thanks for an amazing plugin. Has made our lives a lot easier in wkwebview-land.

Is v2.1.0 gonna go on npmjs? It seems you've fixed a critical bug from v2.0. :-)

URLs are not properly escaped!

After quite a bit of digging, I found out why cordova-plugin-wkwebkit-file-xhr is not correctly loading Mapbox GL JS URLs, even when the following preference is set in config.xml.

<preference name="InterceptRemoteRequests" value="all" />

The following error is displayed any time I want to get a MapBox URL:

ERROR: {"message":"Bad Request"}

The reason is simple (but hard to find!): URLs are not being correctly escaped!
The fix is even simpler.

Replace line 339 in platforms/iOS/[Project Name]/Plugins/CDVWKWebViewFileXhr.m from this:

NSURL *url = [NSURL URLWithString:urlString];

To this:

NSURL *url;
if ([urlString rangeOfString:@"%"].location == NSNotFound) {
    url = [NSURL URLWithString:[urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
} else {
    url = [NSURL URLWithString:urlString];
}

I haven't bothered to create a pull request, as Oracle have stated they will not accept them. You will have to apply this patch manually.

Cookies not stored after app relaunch

I use that plugin to have ability to use 'Set-Cookie' header that required my app. All works fine, (thanks for that a lot) except one thing.
But after relaunch app all cookies looks like not stored and user should login again.
Is there way to store it?

Double encodeURI UTF-8 params

Hi! Thanks for great plugin!

I noticed that when there is UTF-8 parameter value string it makes encodeURI twice.
How to fix this? Thanks!

Screen Shot 2019-08-05 at 14 43 07

How to use with third-party software?

Hi there:

The case is that I'm using a webgl engine (BabylonJS) in one of my cross-platform developments.

My code loads textures, in the form of PNG files, using a specific API, like this:

texGeneric=new BABYLON.Texture("assets/textures/Generic.png",_Scene);
...

This works perfectly.

Also, I need to load a cube map/environment in the form of a DDS file, using this other API:

texEnvironment=BABYLON.CubeTexture.CreateFromPrefilteredData("assets/textures/environment.dds",_Scene);

This doesn't work.

Internally CreateFromPrefilteredData uses XHR, so when ported to a plain Cordova-iOS it can´t find the DDS file, as WKWebView appears to treat local files as if they came from a remote server, even though they're in the app itself, and such requests are blocked.

In this case I thought cordova-plugin-wkwebview-file-xhr could make it work but, when used, the app can't find the (previously working) local files as it output in the remote debug console from Safari:
Cross origin requests are only supported for HTTP.

I have also this relevant output in Xcode:
2018-04-02 12:15:30.245199+0200 GRB Technology[1165:700339] Could not signal service com.apple.WebKit.WebContent: 113: Could not find specified service
2018-04-02 12:15:30.248572+0200 GRB Technology[1165:700339] Could not signal service com.apple.WebKit.Networking: 113: Could not find specified service

Any clue on this? Do I need to add "http://" or something at the beginning of PNG paths?

Thanks for your time.

XMLHttpRequest not working in WKWebView due to CORS restriction

Description: I'm making requests to an API endpoint from Cordova iOS app using $http.get() method which results in the CORS restriction errors.
ERROR: xmlhttprequest cannot load Preflight response is not successful
Observations:

  1. The server sends Access-Control-Allow-Origin response header
  2. Requests are completed when the app is run in Xcode simulator but failed on actual iPad

How can I overcome this issue or is there a workaround for this in WKWebView apps?
Please let me know if more details are required.

Does not seem to work with AWS Javascript SDK for S3

Prior to installing cordova-plugin-wkwebview-engine and cordova-plugin-wkwebview-file-xhr I was able to upload blobs to AWS via their javascript S3 SDK. Now when running the exact same code, the AWS sdk errors out with "null" and no real information.

Here is my code (given a path, bucket_name, file blob, and configured AWS)
var file_name = encodeURIComponent(path.substr(path.lastIndexOf('/')+1));
var params = { Bucket: bucket_name, Key: file_name, ContentType: file.type, Body: file};
var upload = new AWS.S3.ManagedUpload({params: params});
upload.on('httpUploadProgress', function(progressEvent) {
//progress bar stuff
}).send(function(err, data) {
if(err){
console.log(err); //<- shows null
}
else{
//upload success
}
});
}

Response from AWS:
[Log] Error: null (cordova.js, line 1540)
extractError — aws-sdk-2.712.0.min.js:9615:203
callListeners — aws-sdk-2.712.0.min.js:2363
emit — aws-sdk-2.712.0.min.js:2350
emitEvent — aws-sdk-2.712.0.min.js:1576:184
e — aws-sdk-2.712.0.min.js:1453
(anonymous function) — aws-sdk-2.712.0.min.js:1642
(anonymous function) — aws-sdk-2.712.0.min.js:1654
(anonymous function) — aws-sdk-2.712.0.min.js:1462
(anonymous function) — aws-sdk-2.712.0.min.js:1577
callListeners — aws-sdk-2.712.0.min.js:2370
emit — aws-sdk-2.712.0.min.js:2350
emitEvent — aws-sdk-2.712.0.min.js:1576:184
e — aws-sdk-2.712.0.min.js:1453
(anonymous function) — aws-sdk-2.712.0.min.js:1642
(anonymous function) — aws-sdk-2.712.0.min.js:1654
(anonymous function) — aws-sdk-2.712.0.min.js:1462
(anonymous function) — aws-sdk-2.712.0.min.js:1577
callListeners — aws-sdk-2.712.0.min.js:2370
o — aws-sdk-2.712.0.min.js:2356
(anonymous function) — aws-sdk-2.712.0.min.js:2139
(anonymous function) — aws-sdk-2.712.0.min.js:8240
finishRequest — aws-sdk-2.712.0.min.js:6942
(anonymous function) — aws-sdk-2.712.0.min.js:6891:268
(anonymous function) — xhr-polyfill.js:1203
(anonymous function) — xhr-polyfill.js:997
[native code]
(anonymous function) — xhr-polyfill.js:661
[native code]
promiseReactionJob

Any help would be appreciated!

Loading Polymer 3 apps (`<script crossorigin="anonymous">`)

We've been using Cordova and Polymer together for quite a while. Recently things started breaking again, after we moved from WKWebView + local file server to the WKWebView + xhr-plugin approach. From what we could track down a change in Polymer (Polymer/tools@5aebb66) modified how they want to load the scripts. As a result of that change the requests to the scripts to now get send with an additional Origin: null, according to the Safari dev tools. This fails (presumably due to https://issues.apache.org/jira/browse/CB-10143), but in the debugger I also do not see the xhr plugin getting invoked.

I'm still trying to piece things together, and we have found a way to avoid that commit in Polymer. But, with the reasoning of that commit being "closer to the standard", this is of course not a long-term approach.

  1. Is this something that the xhr plugin should have handled, and therefore an actual bug?
  2. Do you have any idea how to maybe debug this further, and/or where/how to fix this?

iOS 12 svg as background getting Origin null

My svg's as background-image in css are not loading
I used

<preference name="InterceptRemoteRequests" value="all" />
<plugin name="cordova-plugin-wkwebview-engine" spec="^1.1.4" />
<plugin name="cordova-plugin-wkwebview-file-xhr" spec="^2.1.1" />

Still getting not allowed due to Origin null over file:///var/containers/Bundle/Application/....
cordova iOS 5.0.0
cordova 7.1
Any help appreciated

Getting "The network connection was lost." when uploading image file

Hi!

I'm getting "The network connection was lost." when uploading file. No matter how file size is(tested on 128kb and 2mb). Here are logs:

Opera Build[4820:554763] Task <0C57E5BB-7A5F-4D18-8391-3A6043AEF13E>.<14> HTTP load failed (error code: -1005 [1:57])
Opera Build[4820:554415] Task <0C57E5BB-7A5F-4D18-8391-3A6043AEF13E>.<14> finished with error - code: -1005
Opera Build[4820:554279] {"error":"The network connection was lost.","underlyingErrorCode":-1005,"id":"a50c-0.870c710c88a06"}

Do I need to fix something on server side? Right now nginx is configured to keepalive 65s.

P.s. Using iOS 12.4.

Remove dependency on cordova-plugin-wkwebview-engine

We want to use this plugin with cordova-plugin-ionic-webview, but this plugin contains <dependency id="cordova-plugin-wkwebview-engine" /> in plugin.xml. cordova-plugin-ionic-webview conflicts with cordova-plugin-wkwebview-engine and we get duplicate symbol errors at build time.

Should this dependency be removed? Anyone who wants to use this probably already installed cordova-plugin-wkwebview-engine.

XHR local file request throwing cross origin error

I realise this has been asked and closed in the previous issues. However, I'm still unable to get this plugin to work after a few hours of going through all the threads. Error details and my environment below:

[Error] XMLHttpRequest cannot load file:///Users/user001/Library/Developer/CoreSimulator/Devices/B928C8B2-1A44-488F-93D6-0039C51CF17F/data/Containers/Bundle/Application/6047BE0D-F397-4105-A6E9-F3B9F8492413/MobileApp.app/www/pages/home.html. Cross origin requests are only supported for HTTP.
testXHR (index.html:112)
onclick (index.html:53)

function testXHR(){
            var xhr = new XMLHttpRequest();
            xhr.addEventListener("loadend", function(evt)
            {
            var data = this.responseText;
            console.log(data);
            });
            
            xhr.open("GET", "pages/home.html");
            xhr.send();
}

engine name="ios" spec="^4.5.4"
plugin name="cordova-plugin-wkwebview-engine" spec="^1.1.4"
plugin name="cordova-plugin-wkwebview-file-xhr" spec="^2.1.1"

IOS : 11.4 running on iPhone 8, 8P, IphoneX simulators and IphoneX device.
Xcode : 9.4.1

Blob urls are loaded incorrectly

Current system tries to load blob urls via File handler if loading page is from file protocol, as blob urls do not contain "://" (they usually have the form of "blob:null/adafalsjiejwqoe")

Plugin not intercepting eventSource or calls from html

It seems that although I set the InterceptRemoteRequests to all

calls not created directly by an ajax call is not intercepted.
As a result eventSource or an img will fail if authentication (cookies) is required.

Is this intentional, or I am missing something.
Currently my workaround is that I initiate a login also by a non intercepted call so I set up the session cookies in both layers.

Also I couldn't make that the origin not to be "null" while according to the documentation this one important feature.

I cannot say that cordova-plugin-wkwebview-file-xhr doesn't do anything either as without the plugin I cannot make any calls because my server needs the AllowUntrustedCerts=on setting, which seems to work. Strange...

Is my configuration correct?








Also support file:// urls

It would be nice if absolute file:// urls were also supported (checking that they point to a resource inside the www folder, of course). For example, the AngularJS template service makes XMLHttpRequest with absolute url to load templates, which then fail. Can be worked around on the Angular side, but would be nice if it worked out of the box.

Thanks for the great plugin!

Can't use fileurl with sandbox ressource

Hello,
This plugin can't get file inside the sandbox but inside the bundle yes

I saw inside the CDVWKWebViewFileXhr.m, you check if the file want to go to the bundle with the method isWebContentResourceSecure.
So why not check if we want to go to the sandbox?

Like to add this method in CDVWKWebViewFileXhr.m :

- (BOOL)isSandBoxResource: (NSURL*) targetURL
{
    NSURL *baseURL = [NSURL fileURLWithPath:NSHomeDirectory()];
    NSString *basePath = [baseURL absoluteString];
    NSString *targetPath = [[targetURL standardizedURL] absoluteString];
    return ([targetPath hasPrefix:basePath]);
}

and add this condition inside readAsText line 178:

    if (![self isWebContentResourceSecure:targetURL] && ![self isSandBoxResource:targetURL]) 

Thanks

Cross-origin error from canvas.ctx.getImageData()

When i call method getImageData from canvas, i get error:
"Unable to get image data from canvas because the canvas has been tainted by cross-origin data".
Example to reproduce this error:
function testCanvas(src) {
var canvas = document.createElement("canvas");
var img = new Image();
img.addEventListener("load", function () {
canvas.getContext("2d").drawImage(img, 0, 0, img.width, img.height, 0, 0, canvas.width, canvas.height);
canvas.getContext("2d").getImageData(0,0,img.width, img.height);
canvas.toDataURL();
});
img.setAttribute("src", src);
}

Works on simulator but not on device for file prot

Hello,

thanks for the work with this plugin!
I have an issue, when running the app on the simulator from xcode it works fine with local file:// resources, but when I debug on my device it doesnt work and fails with the following:
Failed to load resource: The operation couldn’t be completed. Operation not permitted
file:///var/mobile/Containers/Data/Application/B01D6417-EC0C-49D4-9B80-6EC64C2500D6/Library/NoCloud/134816086487-7927-4917-9d8d-8fb72ede76c6.jpg
[Error] Failed to load resource: The operation couldn’t be completed. (kCFErrorDomainCFNetwork error 1.)

FormData send does not work

the error message states that body.keys() is not a function. Looking at FormData prototype in safari reveals that the only function FormData has implemented is append and keys() is indeed missing.

Thankfully, I found a polyfill that adds it at https://github.com/jimmywarting/FormData

For completeness, you may want to include this in your project though, or at least link to it in the readme.

Unable to post message to file://. Recipient has origin null.

I have an application written on vue. It worked until I switched to WkWebView. Then I started to get this error - Unable to post message to file: //. Recipient has origin null. Installing your plugin did not help. Do I have to do anything else in my code?

Mis-parse of relative paths. Alway based-on “www/“ instead of the HTML page.

Case: In "settings/set.html”, read “settings/data.json” using fetch().
Current situation: Fetching “data.json” will get an error. I have to fetch “settings/data.json” to make it work.
Supposed: I should be able to fetch "data.json" directly since they are in the same folder.

It caused many bugs with dynamically loaded resources.

xhr-polyfill setting response status code 400 for remote https calls in airplane mode

Here is the relevant code:

HttpHandler._error = function (reqContext, error, underlyingErrorCode)
{
var isTimeout = (HttpHandler._UNDERLYING_ERROR_CODES.NSURLErrorTimedOut === underlyingErrorCode);
if (isTimeout)
{
reqContext.status = 0;
reqContext.statusText = reqContext.responseText = null;
}
else
{
reqContext.status = 400;
reqContext.statusText = "Bad Request";
reqContext.responseText = error;

Why does it do that? An application should expect 0 status code for network issues, and defined http status codes such as 400 should be expected to only be what comes back from server.

.abort() does not work as expected

I'm using this plugin and I want to abort all pending requests if the user logs out of my app. The abort() function does not do it.

Debugging I see that this._context.delegate is always null so there's no abort function there to be called. I'd appreciate some help with this.

Thanks.

this.response is undefined when responseType is a Blob/ArrayBuffer

Hi I've tested this plugin in my case, a file object with a file url (from upload) and creating a Blob file of it through XHR: MDN Link

var oReq = new XMLHttpRequest();
oReq.open("GET", "file:///myfile.png", true);
oReq.responseType = "blob";

oReq.addEventListener('loadend', function () {
    var res = this.response; // undefined
});

oReq.onload = function(oEvent) {
  var blob = oReq.response;
  // ...
};

oReq.send();

this.response is always undefined. I've also checked this with ajaxData attribute to be null. I'm not sure if Blob responseType is supported with this plugin but I'm also having a CORS exception when requesting to file:/// on a WKWebview.

A similar plugin for Android?

I am also seeing CORS issues on the latest versions of Android.

Is there a possibility that we might see this plugin for Android as well?

Not working on iOS 14

This plugin is not working on iOS 14 devices. Tested on my iPhone 11 Pro running the second Beta of iOS 14.

I am not sure how I should debug this. By using Wireshark I could see a lots of OPTIONS requests. The log of the Browsers Network monitor is not really useful. I will monitor this and keep this issue updated. It may be an issue on Apples side.

Anyone has similar issues?

iPhone X Issue (CSS bottom: 0)

This plugin works perfectly for all iOS devices apart from the new iPhone X. We've experienced that our CSS style of bottom: 0 for something position: absolute doesn't sit right on the bottom. There is a gap between the very bottom of the screen and the element we've positioned. First we thought this could be to account for the "Home bar indicator", but we realised it's quite a bit more than the height given by the CSS constant of env(safe-area-inset-bottom) or constant(safe-area-inset-bottom).

Any information, fixes, or workarounds would be appreciated! Thanks.

Casting non-string headers

First wanted to thank you for the effort of this plugin, it's been making my transition off of UIWebView so much easier for my use cases.

I've noticed one different behavior between the way the normal XHR method works with headers though. Previously if we set header values by enumerating a JSON object and call:
request.setRequestHeader(key, value);

If value is anything other than a string (in my case a number) the original XHR would cast it to a string and use it. It seems like this plugin throws out these values though when going through the header dictionary though:

if (![key isKindOfClass:NSString.class] || ![obj isKindOfClass:NSString.class])
return;
[request setValue:(NSString *)obj forHTTPHeaderField:(NSString *)key];

Would it be possible to add casting for numbers? I don't know Objective-C too well yet but something like this?

NSString* strKey = ![key isKindOfClass:NSString.class] ? [key stringValue] : (NSString *)key;
NSString* strValue = ![obj isKindOfClass:NSString.class] ? [obj stringValue] : (NSString *)obj;
[request setValue:strValue forHTTPHeaderField:strKey];

Thank you!

TypeError: req.dispatchEvent is not a function

Hello,

I get the above error when loading any asset file with a relative path from JS such as templates/config.js. But, initial loading worked perfectly when assets are referenced in the index.html file, when Cordova apparently auto-sets the URLs as so: file:///var/containers/Bundle/Application/67FAC6E7-FDC1-488D-8458-ABCF6872CC02/myApp.app/www/js/printer.js.

The error is

[Error] Unhandled Promise Rejection: TypeError: req.dispatchEvent is not a function. (In 'req.dispatchEvent(event)', 'req.dispatchEvent' is undefined)
	(anonymous function) (xhr-polyfill.js:1000)
	(anonymous function) (util.js:5)
	_presend (xhr-polyfill.js:181)
	send (xhr-polyfill.js:237)
	(anonymous function) (xhr-polyfill.js:1232)
	promiseReactionJob

My project uses jQuery to handle create AJAX calls. All assets are located within www/

Debugging shows this data with a breakpoint just above line 1000 in xhr-polyfill.js:

event: undefined
readyState: undefined
req: 1

Thanks.

Angular ChangeDetection doesn't work

Hi,
does anybody know why the angular ChangeDetection is not working with cordova-plugin-wkwebview-file-xhr? I load data in my angular 9+ project and get the correct response from api but the view can not be refreshed.

import { ChangeDetectionStrategy, ChangeDetectorRef, Component, OnInit } from '@angular/core';

import { ICaseLibrary } from '@shared/model';
import { AdminService } from '../admin.service';

@Component({
    selector: 'app-caselibrary',
    templateUrl: './caselibrary.template.html',
    changeDetection: ChangeDetectionStrategy.OnPush,
})
export class CaseLibraryComponent implements OnInit {
    casesFromDB: ICaseLibrary[];

    constructor(
        private adminService: AdminService,
        private cdRef: ChangeDetectorRef) { }

    ngOnInit(): void {
        this.adminService.getCasesForCaseLibrary().subscribe(
            response => {
                this.casesFromDB = response;
                this.cdRef.markForCheck(); // <== does not work in cordova using the WKWebView
            });
    }
}

As soon as this.cdRef.markForCheck(); is run in NgZone the view is going refreshed:

            this.ngZone.run(() => {   
                this.cdRef.markForCheck();
            });

Does cordova-plugin-wkwebview-file-xhr provides its own promise polyfill causing the angular change detection to break? Do I miss something? How to get the angular change detection work without run markForCheck() in NgZone? My angular code is shared between web, desktop and mobile platforms and the change detection should not be run outside of angular zone. Any idea?

Other request events will be added?

Hello! Thanks for plugin, it's really help me.
But I want to make uploading images from my ionic app. I make a big post request (with base64 encoded image) and I need to listen events 'progress', but they doesn't fired.
Are you plan to add this events?

cordova-ios 6 support

Hi there,

Cordova has released cordova-ios@6 which implements the WKWebView making their wkwebview plugin obsolete.

But for users who still need to use the file:// scheme, this plugin is still necessary if you need to use XHR to local file:// paths.

I would advise making a minor/patch release that limits version 2.x to [email protected], and a new major release that expects cordova-ios@6 and removes the wkwebview engine plugin dependency.

I think this is necessary to solve apache/cordova-ios#883

Object.toString doesn't work as expected with FormData polyfil

The FormData polyfil does not set the toStringTag symbol which will cause Object.toString to incorrectly report these objects as "[object Object]" instead of "[object FormData"]

//This will work...
var fd = new FormData();
fd.toString(); //Outputs "[object FormData"]

//this will not work
var fd = new FormData();
Object.toString.call(fd); //Outputs "[object Object]"

This causes issues when attempting to use multi-part file upload in AngularJS. If you do not specify the content type and post a form using $http, AngularJS is supposed to automatically detect the FormData and set the content type and boundry automatically.

It seems that this can be fixed by setting the Symbol correctly, something like:

  if( 'Symbol' in window && typeof Symbol() === 'symbol'){
    Object.defineProperty( __FormData.prototype, Symbol.toStringTag, {
      get : function(){
        return 'FormData';
      }
    });
  }

Newer XCode restricts webView to be called only from main thread

XCode shows the following runtime errors:
[WKScriptMessage body] must be used from main thread only
[WKScriptMessage webView] must be used from main thread only
This is a restriction since iOS 11 (so it is relatively recent)

Offending lines are 407-409 of CDVWKWebViewFileXhr.m

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.