Showing posts with label webview. Show all posts
Showing posts with label webview. Show all posts

Wednesday, August 1, 2018

React Native IOS 11.3 - 11.4 Error: JavaScriptCore JSC::JSLock::DropAllLocks::DropAllLocks

Leave a Comment
react-native-cli: 2.0.1 react-native: 0.53.3 ios 11.3.0 - 11.4.1 

enter image description here

Crashed: WebThread 0  JavaScriptCore                 0x18a929464 JSC::JSLock::DropAllLocks::DropAllLocks(JSC::VM&) + 176 1  JavaScriptCore                 0x18a929438 JSC::JSLock::DropAllLocks::DropAllLocks(JSC::VM&) + 132 2  WebCore                        0x18b671cec SendDelegateMessage(NSInvocation*) + 360 3  WebKitLegacy                   0x18cd96c68 CallDelegate(void (*)(), WebView*, objc_object*, objc_selector*, objc_object*, objc_object*, objc_object*) + 144 4  WebKitLegacy                   0x18cd0a8d0 WebFrameLoaderClient::dispatchDidFailLoading(WebCore::DocumentLoader*, unsigned long, WebCore::ResourceError const&) + 276 5  WebCore                        0x18b6a0df0 WebCore::ResourceLoadNotifier::didFailToLoad(WebCore::ResourceLoader*, WebCore::ResourceError const&) + 128 6  WebCore                        0x18b6a08a8 WebCore::ResourceLoader::cancel(WebCore::ResourceError const&) + 464 7  WebCore                        0x18b6a0634 WebCore::ResourceLoader::cancel() + 64 8  WebCore                        0x18c5aa474 WebCore::CachedResource::removeClient(WebCore::CachedResourceClient&) + 264 9  WebCore                        0x18c56ea94 WebCore::MediaResource::~MediaResource() + 64 10 WebCore                        0x18c56eb44 WebCore::MediaResource::~MediaResource() + 12 11 libobjc.A.dylib                0x18268aef4 object_cxxDestructFromClass(objc_object*, objc_class*) + 148 12 libobjc.A.dylib                0x182698990 objc_destructInstance + 68 13 libobjc.A.dylib                0x1826989f8 object_dispose + 16 14 WebCore                        0x18caed6d0 -[WebCoreNSURLSessionDataTask dealloc] + 320 15 CoreFoundation                 0x1833a24e4 -[__NSDictionaryM dealloc] + 164 16 AVFoundation                   0x188ff7448 -[AVAssetCustomURLBridgeForNSURLSession dealloc] + 68 17 AVFoundation                   0x189043580 -[AVAssetResourceLoader dealloc] + 356 18 AVFoundation                   0x188f26214 -[AVURLAsset dealloc] + 248 19 WebCore                        0x18b823464 WebCore::MediaPlayerPrivateAVFoundationObjC::cancelLoad() + 240 20 WebCore                        0x18b82283c WebCore::MediaPlayerPrivateAVFoundationObjC::~MediaPlayerPrivateAVFoundationObjC() + 336 21 WebCore                        0x18b82333c WebCore::MediaPlayerPrivateAVFoundationObjC::~MediaPlayerPrivateAVFoundationObjC() + 12 22 WebCore                        0x18c709c00 WebCore::MediaPlayer::~MediaPlayer() + 244 23 WebCore                        0x18c709c68 WebCore::MediaPlayer::~MediaPlayer() + 12 24 WebCore                        0x18c3f0394 WebCore::HTMLMediaElement::~HTMLMediaElement() + 1336 25 WebCore                        0x18c44f2a0 WebCore::HTMLVideoElement::~HTMLVideoElement() + 176 26 JavaScriptCore                 0x18a905a5c void JSC::MarkedBlock::Handle::specializedSweep<true, (JSC::MarkedBlock::Handle::EmptyMode)1, (JSC::MarkedBlock::Handle::SweepMode)0, (JSC::MarkedBlock::Handle::SweepDestructionMode)1, (JSC::MarkedBlock::Handle::ScribbleMode)0, (JSC::MarkedBlock::Handle::NewlyAllocatedMode)1, (JSC::MarkedBlock::Handle::MarksMode)1, JSC::JSDestructibleObjectDestroyFunc>(JSC::FreeList*, JSC::MarkedBlock::Handle::EmptyMode, JSC::MarkedBlock::Handle::SweepMode, JSC::MarkedBlock::Handle::SweepDestructionMode, JSC::MarkedBlock::Handle::ScribbleMode, JSC::MarkedBlock::Handle::NewlyAllocatedMode, JSC::MarkedBlock::Handle::MarksMode, JSC::JSDestructibleObjectDestroyFunc const&) + 196 27 JavaScriptCore                 0x18a90446c void JSC::MarkedBlock::Handle::finishSweepKnowingHeapCellType<JSC::JSDestructibleObjectDestroyFunc>(JSC::FreeList*, JSC::JSDestructibleObjectDestroyFunc const&)::'lambda'()::operator()() const + 348 28 JavaScriptCore                 0x18a903fa4 void JSC::MarkedBlock::Handle::finishSweepKnowingHeapCellType<JSC::JSDestructibleObjectDestroyFunc>(JSC::FreeList*, JSC::JSDestructibleObjectDestroyFunc const&) + 320 29 JavaScriptCore                 0x18a903e58 JSC::JSDestructibleObjectHeapCellType::finishSweep(JSC::MarkedBlock::Handle&, JSC::FreeList*) + 32 30 JavaScriptCore                 0x18a68597c JSC::MarkedBlock::Handle::sweep(JSC::FreeList*) + 372 31 JavaScriptCore                 0x18a67c064 JSC::IncrementalSweeper::sweepNextBlock() + 132 32 JavaScriptCore                 0x18a05e7fc JSC::IncrementalSweeper::doWork() + 72 33 JavaScriptCore                 0x18a949864 JSC::JSRunLoopTimer::timerDidFireCallback(__CFRunLoopTimer*, void*) + 76 34 CoreFoundation                 0x18347baa8 __CFRUNLOOP_IS_CALLING_OUT_TO_A_TIMER_CALLBACK_FUNCTION__ + 28 35 CoreFoundation                 0x18347b76c __CFRunLoopDoTimer + 864 36 CoreFoundation                 0x18347b010 __CFRunLoopDoTimers + 248 37 CoreFoundation                 0x183478b60 __CFRunLoopRun + 2168 38 CoreFoundation                 0x183398da8 CFRunLoopRunSpecific + 552 39 WebCore                        0x18b65c2d4 RunWebThread(void*) + 592 40 libsystem_pthread.dylib        0x1830f9220 _pthread_body + 272 41 libsystem_pthread.dylib        0x1830f9110 _pthread_body + 290 42 libsystem_pthread.dylib        0x1830f7b10 thread_start + 4 

The app displays some html content in an WebView. All I know about this crash is that it could be related to embedded videos widgets:

https://forums.developer.apple.com/thread/101477

Is this bug related to React Native platform? Would an update of RN fix the issue?

This issue could be related to Javascript core crash when using YouTube iframe player in UIWebView in iOS 11.3 because of the React Native WebView...

The app content which is displayed in webview can be normal html text or instagram, facebook or youtube scripts/iframes ...

0 Answers

Read More

Saturday, July 21, 2018

Electron Manipulate/Intercept WebView Requests and Responses

Leave a Comment

I want to create an Electron app that will use webview to display 3rd party content.

I would like to be able to intercept all requests and responses from this webview. Sometimes I would like to manipulate this content, other times I would like to log it, and other times I’d like to do nothing.

As one example for the responses, maybe a web server will respond with TypeScript code, maybe I want to take that response, and compile it to standard JavaScript.

I have looked into this page but it looks like it is only possible to cancel requests, and manipulate the headers. The WebRequest API doesn't look to fit the needs of my use case since it only allows very minor manipulations of requests and responses.

I have also considered setting up some time of web server that can act as a proxy, but I have concerns about that. I want to maintain user privacy, and I want to ensure that to the web servers that host the 3rd party content it looks like the request is coming from a browser like environment (ex. Electron webview) instead of a server. I know I can manipulate requests with the headers I send and such, but this whole solution is getting to be a lot more complicated, then I would like, but might be the only option.

Any better ways to achieve this, and have more control over the Electron webview?

1 Answers

Answers 1

I think you should look into The Protocol API. it works as a proxy internally. say you wanna the user open http://www.google.com and see content like you've been conned!.

const { protocol } = require("electron");    const content = new Buffer("you've been conned!");    protocol.interceptBufferProtocol("http", (request, result) => {    if (request.url === "http://www.google.com")      return result(content);    ... // fetch other http protocol content and return to the electron  });

there's lots of work to do, comparing to the WebRequest API. but it's much simpler than a independent local proxy.

Read More

Wednesday, May 2, 2018

Double message on ios when get geolocation

Leave a Comment

I have created an ios app (Xcode) with a single WebKit View component that loads an external website. This website tries to get the current geolocation with this Javascript: navigator.geolocation.

This all works fine, but the problem is, I get 2 messages:

  1. First a message for the app: 'Allow "NameApp" to access your location while you are using the app?'
  2. Second a message for the webview: 'https://mywebsite.com would like to use your current location'.

I have seen similar questions about this issue, but they all went about a native/offline Cordova app. I have an online app in my Webview.

How can I prevent this double message? Or a workaround for this problem?

0 Answers

Read More

Wednesday, April 25, 2018

How to use native android webview in Qt C++ using QAndroidJniObject

Leave a Comment

I would like to use the Android WebView in my qml application. The default WebView object provided uses native rendering but several features are missing (for example the ability to intercept network requests and block them). I know that Qt allows you to call native Java API using QAndroidJniObject. Is it possible to use that to create a Qt wrapper around the native Android WebView? If yes, how can I achieve that?

1 Answers

Answers 1

This is tricky. You basically need to create a new class during runtime that overrides shouldInterceptRequest:

public class SuperDuperUniqueNameForMyWebViewClient extends android.webkit.WebViewClient {     // constructor etc...     @Override     public android.webkit.WebResourceResponse shouldInterceptRequest(android.webkit.WebView view, android.webkit.WebResourceRequest request) {         // implement your logic here     } } 

To create the class dynamically, you muste compile the code on-the-fly in Java:

String source = ...; int result = com.sun.tools.javac.Main.compile(new String[]{source});  // parameter is an array 

Which in Qt C++ gives us this:

QString source = ...;  // Here you need to provide the Java code for your class QAndroidJniObject sourceObject = QAndroidJniObject::fromString(source); jobjectArray sourceObjectArray = sourceObject.object<jobjectArray>();  // this is probably not correct jint result = QAndroidJniObject::callStaticMethod<jint>("com/sun/tools/javac/Main",                                                        "compile"                                                        "([Ljava/lang/String;)I",                                                        jobjectArray); 

After that you should be able create a web view client with your own class and use it:

QAndroidJniObject myWebViewClient{"SuperDuperUniqueNameForMyWebViewClient"}; 

Take all of this with a grain of salt, as it is from the top of my head and I haven't tested it. At the very least it should push you in the right direction, though.

Read More

Tuesday, April 10, 2018

Detect whether touch was Apple Pencil or finger in webview (react native)

Leave a Comment

In safari mobile, touches can be classified as Apple Pencil vs other (finger/ mouse) using:

event.touches[0].touchType === 'stylus' //pencil event.touches[0].touchType !== 'stylus' //other 

However all events received in a react native webview (both for Apple Pencil and using a finger) are receiving:

touchType === 'direct' //inside webview, both pencil and other 

How can I detect a touch with the Apple Pencil inside a webview?

Apparently event.touches[0] > 0 is another possibility but this is also being set to 0 for both types in webview.

(Not sure if this is an issue with react native or a built-in limitation of webviews).

Related:

2 Answers

Answers 1

I resolved this issue by replacing the React Native WebView component with WKWebView component from from https://github.com/CRAlpha/react-native-wkwebview

i.e. Replace import { WebView } from 'react-native' with import WKWebView from 'react-native-wkwebview-reborn'

This required various modifications and workarounds but was ultimately successful, and events now include the extra parameters such as:

  • touchType
  • force
  • altitudeAngle
  • azimuthAngle

It appears that the older WebView may not support the additional event parameters associated with Pencil/Stylus (but it's also possible that I was using a wrong/old version or perhaps React Native does not pass these through from the native WebView component. I would be happy to update with more detail if anyone can clarify).

Answers 2

If you look at iOS 8 release date

17 September 2014

And Apple pencil release date

11 November 2015

And Apple's force touch release date

September 9, 2014

Now if you look at the below article from apple

https://developer.apple.com/documentation/webkit/wkwebview

Important

Starting in iOS 8.0 and OS X 10.10, use WKWebView to add web content to your app. Do not use UIWebView or WebView.

So it may be possible the WKWebView has betters support for these things compared to UIWebView. But it can't be confirmed without experimentation as no documentation with clear differences between the two is available

There was huge discussion on using WKWebView by default on iOS8+ for react native. You can find the same on below

https://github.com/facebook/react-native/issues/321

You can see comment from WKWebView react component maintainer

Maintainer of react-native-wkwebview here. I agree that there are limited benefits for this repo to be merged into core, one of them being Expo support (Expo still uses UIWebView). But I think this is more of an issue for Expo, rather than React Native.

IMO, React Native should focus on the "core" bridges and this component should happily live as a 3rd party component. This makes it easier for people to actually contribute to this project. Also, it means flexible release schedule (as opposed to the monthly release schedule of React Native)

And I agree with @brunolemos that improving React Native docs is a better way to make people more aware of the decision regarding UIWebView and WKWebView and point them to the solution.

So I think it may be possible that WKWebView has more capabilities in events than the deprecate UIWebView. But unfortunately after hours of digging I couldn't find any such official information. I would have added some extra information if I had iPhone/iPad with me to experiment with.

I tried with simulator and I get the below fields in events for both UIWebView and WKWebView

WKWebView

Event

UIWebView

UIWevView

The JSFiddle I used

https://jsfiddle.net/J4djY/166/

But since I don't have a physical device, I can't confirm some of the observations

Read More

Monday, March 26, 2018

Detect whether touch was Apple Pencil or finger in webview (react native)

Leave a Comment

In safari mobile, touches can be classified as Apple Pencil vs other (finger/ mouse) using:

event.touches[0].touchType === 'stylus' //pencil event.touches[0].touchType !== 'stylus' //other 

However all events received in a react native webview (both for Apple Pencil and using a finger) are receiving:

touchType === 'direct' //inside webview, both pencil and other 

How can I detect a touch with the Apple Pencil inside a webview?

Apparently event.touches[0] > 0 is another possibility but this is also being set to 0 for both types in webview.

(Not sure if this is an issue with react native or a built-in limitation of webviews).

Related:

0 Answers

Read More

Saturday, March 3, 2018

Preload multiple local WebViews

Leave a Comment

Because I could just find some outdated information / not working solutions to my problem I decided to ask this kind of question again. (See outdated / wrong solutions:)


My app is separated in one native part and one HTML part. The HTML is saved as a local file (index.html) and should be load into the myWebView view.

@IBOutlet weak var myWebView: UIWebView! func loadWebview() {     let url = Bundle.main.url(forResource: "index", withExtension: "html")     let request = URLRequest(url: url!)     myWebView.loadRequest(request)     myWebView.scrollView.isScrollEnabled = false     myWebView.allowsLinkPreview = false     myWebView.delegate = self } 

Because my DOM tree is very large, switching from the native part to the web part (on button click) takes quite a long time at -least for the first time switching- because afterward, I'm sure the webView-request gets cached.

To my question: How can I preload the WebView on app init to avoid the white screen (maybe 0.5s - 1s duration) when switching from the native to the Web part?

EDIT:

The WKWebView is displaying the scrollbar while the UIWebView was not!

Using (like with UIWebView) this styles:

::-webkit-scrollbar {      display: none; } 

is not working and adding these lines:

webview.scrollView.showsHorizontalScrollIndicator = false webview.scrollView.showsVerticalScrollIndicator = false 

is also not working at all.

1 Answers

Answers 1

Firstly, you should switch to WKWebView, UIVewView is no longer recommended to be used by Apple.

Secondly, you can create a pool of web views that get created and asked to load when the app starts. This way by the time the user switches to the web interface the web view might've got a chance to fully load.

For this you can use a class like this:

/// Keeps a cache of webviews and starts loading them the first time they are queried class WebViewPreloader {     var webviews = [URL: WKWebView]()       /// Registers a web view for preloading. If an webview for that URL already     /// exists, the web view reloads the request     ///     /// - Parameter url: the URL to preload     func preload(url: URL) {         webview(for: url).load(URLRequest(url: url))     }      /// Creates or returns an already cached webview for the given URL.     /// If the webview doesn't exist, it gets created and asked to load the URL     ///     /// - Parameter url: the URL to prefecth     /// - Returns: a new or existing web view     func webview(for url: URL) -> WKWebView {         if let cachedWebView = webviews[url] { return cachedWebView }          let webview = WKWebView(frame: .zero)         webview.load(URLRequest(url: url))         webviews[url] = webview         return webview     } } 

and ask it to preload the url sometimes during the app startup:

// extension added for convenience, as we'll use the index url in at least // two places extension Bundle {     var indexURL: URL { return self.url(forResource: "index", withExtension: "html")! } }  webviewPreloader.preload(url: Bundle.main.indexURL) 

Thirdly, you might need to use a container view instead of the actual web view, in your controller:

@IBOutlet weak var webviewContainer: UIView! 

What remains is to add the preloaded web view to the container when needed:

func loadWebview() {     // retrieve the preloaded web view, add it to the container     let webview = webviewPreloader.webview(for: Bundle.main.indexURL)     webview.frame = webviewContainer.bounds     webview.translatesAutoresizingMaskIntoConstraints = true     webview.autoresizingMask = [.flexibleWidth, .flexibleHeight]     webviewContainer.addSubview(webview) } 

And not lastly, be aware that keeping alive instances of web views, might carry performance penalties - memory and CPU-wise.

Read More

Thursday, January 11, 2018

Webview throws ERR_NAME_NOT_RESOLVED during logout

Leave a Comment

I have an application that loads through webview. I am able to login into application which has been launched through webview. But during logout, it keeps throwing ERR_NAME_NOT_RESOLVED error for the server it is sending logout request against.

When I do the same login/logout in regular browser on mobile, i still get the same error on browser. When I do the same login/logout in regular browser on PC, it works perfectly fine.

Not entirely sure if this is a webview using Chromium client issue or issue with server?

1 Answers

Answers 1

  1. On the 3G in your mobile emulator
  2. And on the Cellular Data
  3. Make sure 3G Symbol appears above the signal strength symbol

And try to add permissions in your manifest to access internet:

<uses-permission android:name="android.permission.INTERNET" /> </manifest> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> 

As stated here.

Read More

Friday, December 29, 2017

How do I make JavaFX's webview render even when not visible due to being in another tab?

Leave a Comment

I'm loading a website on a JavaFX WebView and after a while taking a screenshot with something like:

WritableImage image = webView.snapshot(null, null); 

If I'm looking at that WebView that works fine, but if it's hidden by being in a tab that is not in the foreground (I'm not sure about other cases of hiding it), then, the screenshot is of the appropriate site, but entirely blank.

How can I force the WebView to render even if not visible?

During this time, webView.isVisible() is true.

I found there's a method in WebView called isTreeReallyVisible() and currently it contains:

private boolean isTreeReallyVisible() {     if (getScene() == null) {         return false;     }      final Window window = getScene().getWindow();      if (window == null) {         return false;     }      boolean iconified = (window instanceof Stage) ? ((Stage)window).isIconified() : false;      return impl_isTreeVisible()            && window.isShowing()            && window.getWidth() > 0            && window.getHeight() > 0            && !iconified; } 

When the WebView is hidden by being in a non-foreground tab, impl_isTreeVisible() is false (all other factors in the return statement are true). That method is on Node and looks like this:

/**  * @treatAsPrivate implementation detail  * @deprecated This is an internal API that is not intended for use and will be removed in the next version  */ @Deprecated public final boolean impl_isTreeVisible() {     return impl_treeVisibleProperty().get(); }  /**  * @treatAsPrivate implementation detail  * @deprecated This is an internal API that is not intended for use and will be removed in the next version  */ @Deprecated protected final BooleanExpression impl_treeVisibleProperty() {     if (treeVisibleRO == null) {         treeVisibleRO = new TreeVisiblePropertyReadOnly();     }     return treeVisibleRO; } 

I could have overriden impl_treeVisibleProperty() to provide my own implementation, but WebView is final, so, I cannot inherit from it.

Another completely different situation to being minimized (iconified) or on a hidden tab is to have the stage completely hidden (as in, running in the tray bar). When in that mode, even if I can get rendering to happen, the WebView doesn't resize. I call webView.resize() and then take a screenshot and the screenshot is of the appropriate size but the actual rendered page is of whatever size the WebView was before.

Debugging this sizing behavior in shown and hidden stages, I found that eventually we get to Node.addToSceneDirtyList() that contains:

private void addToSceneDirtyList() {     Scene s = getScene();     if (s != null) {         s.addToDirtyList(this);         if (getSubScene() != null) {             getSubScene().setDirty(this);         }     } } 

When in hidden mode, getScene() returns null, unlike what happens when it's being show. That means that s.addToDirtyList(this) is never called. I'm not sure if this is the reason why it doesn't get properly resized.

There's a bug about this, a very old one, here: https://bugs.openjdk.java.net/browse/JDK-8087569 but I don't think that's the whole issue.

I'm doing this with Java 1.8.0_151. I tried 9.0.1 to see if it would behave differently as it is my understanding that WebKit was upgraded, but no, it's the same.

3 Answers

Answers 1

Reproducing Pablo's problem here: https://github.com/johanwitters/stackoverflow-javafx-webview.

Pablo suggested to override WebView and adjust some methods. That doesn't work given it's a final class and a private member. As an alternative, I've used javassist to rename a method and replace the code with the code that I want it to execute. I've "replaced" the contents of method handleStagePulse, as shown below.

public class WebViewChanges { //    public static String MY_WEBVIEW_CLASSNAME = WebView.class.getName();      public WebView newWebView() {         createSubclass();         return new WebView();     }      // https://www.ibm.com/developerworks/library/j-dyn0916/index.html     boolean created = false;     private void createSubclass() {         if (created) return;         created = true;         try         {             String methodName = "handleStagePulse";              // get the super class             CtClass webViewClass = ClassPool.getDefault().get("javafx.scene.web.WebView");              // get the method you want to override             CtMethod handleStagePulseMethod = webViewClass.getDeclaredMethod(methodName);              // Rename the previous handleStagePulse method             String newName = methodName+"Old";             handleStagePulseMethod.setName(newName);              //  mnew.setBody(body.toString());             CtMethod newMethod = CtNewMethod.copy(handleStagePulseMethod, methodName, webViewClass, null);             String body = "{" +                     "  " + Scene.class.getName() + ".impl_setAllowPGAccess(true);\n" +                     "  " + "final " + NGWebView.class.getName() + " peer = impl_getPeer();\n" +                     "  " + "peer.update(); // creates new render queues\n" + //                    "  " + "if (page.isRepaintPending()) {\n" +                     "  " + "   impl_markDirty(" + DirtyBits.class.getName() + ".WEBVIEW_VIEW);\n" + //                    "  " + "}\n" +                     "  " + Scene.class.getName() + ".impl_setAllowPGAccess(false);\n" +                     "}\n";             System.out.println(body);             newMethod.setBody(body);             webViewClass.addMethod(newMethod);               CtMethod isTreeReallyVisibleMethod = webViewClass.getDeclaredMethod("isTreeReallyVisible");         }         catch (Exception e)         {             e.printStackTrace();         }     } } 

This snippet is called from the WebViewSample which opens 2 tabs. One with a "snapshot" button, another with the WebView. As Pablo pointed out, the tab with the WebView needs to be the second tab to be able to reproduce.

package com.johanw.stackoverflow;  import javafx.application.Application; import javafx.embed.swing.SwingFXUtils; import javafx.event.EventHandler; import javafx.geometry.HPos; import javafx.geometry.Pos; import javafx.geometry.VPos; import javafx.scene.Group; import javafx.scene.Node; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.control.Tab; import javafx.scene.control.TabPane; import javafx.scene.image.WritableImage; import javafx.scene.input.MouseEvent; import javafx.scene.layout.*; import javafx.scene.paint.Color; import javafx.scene.web.WebEngine; import javafx.scene.web.WebView; import javafx.stage.Stage;  import javax.imageio.ImageIO; import java.awt.image.RenderedImage; import java.io.File; import java.io.IOException;   public class WebViewSample extends Application {     private Scene scene;     private TheBrowser theBrowser;      private void setLabel(Label label) {         label.setText("" + theBrowser.browser.isVisible());     }      @Override     public void start(Stage primaryStage) {         primaryStage.setTitle("Tabs");         Group root = new Group();         Scene scene = new Scene(root, 400, 250, Color.WHITE);          TabPane tabPane = new TabPane();          BorderPane borderPane = new BorderPane();          theBrowser = new TheBrowser();         {             Tab tab = new Tab();             tab.setText("Other tab");              HBox hbox0 = new HBox();             {                 Button button = new Button("Screenshot");                 button.addEventHandler(MouseEvent.MOUSE_PRESSED,                         new EventHandler<MouseEvent>() {                             @Override                             public void handle(MouseEvent e) {                                 WritableImage image = theBrowser.getBrowser().snapshot(null, null);                                 File file = new File("test.png");                                 RenderedImage renderedImage = SwingFXUtils.fromFXImage(image, null);                                 try {                                     ImageIO.write(                                             renderedImage,                                             "png",                                             file);                                 } catch (IOException e1) {                                     e1.printStackTrace();                                 }                              }                         });                 hbox0.getChildren().add(button);                 hbox0.setAlignment(Pos.CENTER);             }              HBox hbox1 = new HBox();             Label visibleLabel = new Label("");             {                 hbox1.getChildren().add(new Label("webView.isVisible() = "));                 hbox1.getChildren().add(visibleLabel);                 hbox1.setAlignment(Pos.CENTER);                 setLabel(visibleLabel);             }             HBox hbox2 = new HBox();             {                 Button button = new Button("Refresh");                 button.addEventHandler(MouseEvent.MOUSE_PRESSED,                         new EventHandler<MouseEvent>() {                             @Override                             public void handle(MouseEvent e) {                                 setLabel(visibleLabel);                             }                         });                 hbox2.getChildren().add(button);                 hbox2.setAlignment(Pos.CENTER);             }             VBox vbox = new VBox();             vbox.getChildren().addAll(hbox0);             vbox.getChildren().addAll(hbox1);             vbox.getChildren().addAll(hbox2);             tab.setContent(vbox);             tabPane.getTabs().add(tab);         }         {             Tab tab = new Tab();             tab.setText("Browser tab");             HBox hbox = new HBox();             hbox.getChildren().add(theBrowser);             hbox.setAlignment(Pos.CENTER);             tab.setContent(hbox);             tabPane.getTabs().add(tab);         }          // bind to take available space         borderPane.prefHeightProperty().bind(scene.heightProperty());         borderPane.prefWidthProperty().bind(scene.widthProperty());          borderPane.setCenter(tabPane);         root.getChildren().add(borderPane);         primaryStage.setScene(scene);         primaryStage.show();     }      public static void main(String[] args){         launch(args);     } }  class TheBrowser extends Region {      final WebView browser;     final WebEngine webEngine;      public TheBrowser() {         browser = new WebViewChanges().newWebView();         webEngine = browser.getEngine();         getStyleClass().add("browser");         webEngine.load("http://www.google.com");         getChildren().add(browser);      }     private Node createSpacer() {         Region spacer = new Region();         HBox.setHgrow(spacer, Priority.ALWAYS);         return spacer;     }      @Override protected void layoutChildren() {         double w = getWidth();         double h = getHeight();         layoutInArea(browser,0,0,w,h,0, HPos.CENTER, VPos.CENTER);     }      @Override protected double computePrefWidth(double height) {         return 750;     }      @Override protected double computePrefHeight(double width) {         return 500;     }      public WebView getBrowser() {         return browser;     }      public WebEngine getWebEngine() {         return webEngine;     } } 

I've not succeeded in fixing Pablo's problem, but hopefully the suggestion to use javassist might help.

I'm sure: To be continued...

Answers 2

I would consider reloading page at the suitable moment using this command:

webView.getEngine().reload(); 

Also try to change parameter SnapshotParameters in method snapShot

If it would not work then I would consider storing Image in memory when WebView is being rendered on screen.

Answers 3

If you go by logical implementation of snapshot, only things that are visible on screen are taken as a snapshot. For taking snapshot of the web view, you can either make it automatically visible by clicking on the tab inside which the view is rendered just before taking the snapshot. Or you can manually click on the tab and take the screenshot. I think no API allows to take snapshot of hidden part as logically it will voilate the concept of hidden things. Code for taking snapshot is already available with you. You can click, or Load the tab like:

You can add a selectionChangedListener or you can do the load just before the snapshot.

addItemTab.setOnSelectionChanged(event -> loadTabBasedFXML(addItemTab, "/view/AddItem.fxml"));  private void loadTabBasedFXML(Tab tab, String fxmlPath) {         try {             AnchorPane anchorPane = FXMLLoader.load(this.getClass().getResource(fxmlPath));             tab.setContent(anchorPane);         } catch (IOException e) {         }     } 
Read More

Thursday, December 14, 2017

Xamarin.Forms on iOS 11.1.2: Webview loads a bigger font

Leave a Comment

I'm using Xamarin.Forms to load an internet's webpage (requirements of the client, please don't judge me), the problem is that in iOS the webpage appears to be bigger that it is.

I don't have any custom render on iOS.

Here is the website loaded on safari on a iPhone 6 iOS 11.1.2

And here is loaded on the webview

MainPage.xaml

<?xml version="1.0" encoding="utf-8" ?> <ContentPage xmlns="http://xamarin.com/schemas/2014/forms"              xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"              xmlns:local="clr-namespace:Juppie"              x:Class="Juppie.MainPage">              <Grid>      <WebView x:Name="Navegador" Source="http://empleosapp.caonainteractive.com/"      WidthRequest="1000" HeightRequest="1000" IsVisible="{Binding Path=HayInternet}" ></WebView>     <ActivityIndicator IsRunning="{Binding Path=Navegando}" IsVisible="{Binding Path=Navegando}"         VerticalOptions="CenterAndExpand"                                HorizontalOptions="CenterAndExpand"                                RelativeLayout.XConstraint="{ConstraintExpression Type=RelativeToParent,                                         Property=Height,                                         Factor=0.33}"                                RelativeLayout.YConstraint="{ConstraintExpression Type=RelativeToParent,                                         Property=Height,                                         Factor=0.33}"/>     </Grid>   </ContentPage> 

MainPage.xaml.cs

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; using Plugin.Connectivity; using System.ComponentModel;  namespace Juppie {     public partial class MainPage : ContentPage, INotifyPropertyChanged     {         public event PropertyChangedEventHandler PropertyChanged;          public MainPage()         {             InitializeComponent();              Navegador.Navigating += Navegador_Navigating;             Navegador.Navigated += (sender, e) => { Navegando = false; };             HayInternet = true;             BindingContext = this;         }         bool hayInternet;          public bool HayInternet         {             get             {                 return hayInternet;             }              set             {                 hayInternet = value;                  PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("HayInternet"));                  EvaluarInternet();             }         }         bool navegando;          public bool Navegando         {             get             {                 return navegando;             }              set             {                 navegando = value;                 PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("Navegando"));              }         }          public async void EvaluarInternet(){             if (!HayInternet)             {              await DisplayAlert("Aviso","Se requiere conexion a internet para emplear esta aplicacion", "OK");             }         }          protected override void OnAppearing()         {             HayInternet = CrossConnectivity.IsSupported && CrossConnectivity.Current.IsConnected;              CrossConnectivity.Current.ConnectivityChanged += (sender, args) =>             {                 HayInternet = args.IsConnected;             };              base.OnAppearing();         }          protected override bool OnBackButtonPressed()         {             if (Navegador.CanGoBack)             {                 Navegador.GoBack();                 return false;             }              return base.OnBackButtonPressed();         }          void Navegador_Navigating(object sender, WebNavigatingEventArgs e)         {             Navegando = true;             if (e.Url.Contains("/banner"))             {                 e.Cancel = true;                  var uri = new Uri(e.Url.Replace("/banner", ""));                 Device.OpenUri(uri);             }         }     } } 

I tried with a custom render and set the scalePageToFit = false, without success. If anyone knows how can I fix this, please let me know.

4 Answers

Answers 1

Xaml: - VerticalOptions="FillAndExpand" seems to fill the HeightRequest and WidthRequest property specification requirements for the WebView to render in a StackLayout - in a Grid it seems to render anyway:

<Grid>     <WebView x:Name="webView"              VerticalOptions="FillAndExpand"              Source="https://www.xamarin.com/"/> </Grid> 

Renderer, ScalesPageToFit is false by default (at least in the simulator with iPhone SE 11.2)

[assembly: ExportRenderer(typeof(WebView), typeof(MyWebViewRenderer))] namespace MyNamespace.iOS {     public class MyWebViewRenderer : WebViewRenderer     {         protected override void OnElementChanged(VisualElementChangedEventArgs e)         {             base.OnElementChanged(e);              if (NativeView != null && e.NewElement != null)             {                 var webView = ((UIWebView)NativeView);                 webView.ScalesPageToFit = true;             }         }     } } 

The screenshots below are from the simulator with iPhone SE.

ScalesPageToFit = true:

enter image description here

ScalesPageToFit = false: enter image description here

Answers 2

Is it possible that the sizing is overwritten by the accessability-settings from the iPhone?

See Settings-App -> General -> Accessability -> Bigger Text

(freely translated from german, actual menu entries may be named different)

Answers 3

I have faced the same issue.

In Xamarin.Forms App resolution is based on the Launch screen. If you are using Assets (LaunchImage) for Launch screen. Then your app resolution is set as per LaunchImage.

The best solution is: use storyboard (LaunchScreen.storyboard) or XIB for Launch screen. This improves your App UI. like font size and App resolution

Answers 4

Tested on my iPhone 6 and the app was showing the same size of font as Safari. I also tested with larger system font in But I did notice that when the activity indicator was running, my font size became smaller and it turned normal after the activity indicator disappear, the font size in the app.

Maybe the font size issue was cause by the side effect of any additional stuff like a Nuget packages or Activity indicator?

You could try to use a new empty form and load only the Webview to compare the differences.

By the way, your app appearance is very alike with iPhone with turned on Display Zoom function.

Before turn on Display Zoom:

enter image description here

After turned on Display Zoom:

enter image description here

Read More

Tuesday, December 5, 2017

JavaScript not executed in WKWebView

Leave a Comment

Since I'm going a bit crazy with this one, I've decided to give it another try and post about it here.

So...

I have a simple Swift/Cocoa application with a WKWebView in it.

I load a local HTML file (which - along with the rest of the .css/.js dependencies - is being copied to the bundle inside a /web folder).

Here's the complete code:

<!DOCTYPE html> <html>     <head>         <title>IBAN Validator</title>         <meta name="viewport" content="width=device-width"/>         <meta charset="UTF-8">          <link href="style/font-awesome.min.css" type="text/css" rel="stylesheet"/>         <link href="style/electriq.css" type="text/css" rel="stylesheet"/>         <link href="style/custom.css" type="text/css" rel="stylesheet" />     </head>     <body>         <!-- window/ -->         <div class="window">             <div class="content" style="text-align: center">                 <div class="panel">                     <input id="iban" type="text" style="text-align:center;"><br/>                     <div style="position: relative; max-width: 150px; width: 100%; margin: 0 auto">                         <a id="validateButton" href="#" class="button" style="width:150px;">Validate</a>                         <span id="resultValid" style="position:absolute; left: calc(100% + 20px); top: 10%; color: green; font-size: 20px; display:none;"><i class="fa fa-check"></i></span>                         <span id="resultInvalid" style="position:absolute; left: calc(100% + 20px); top: 10%; color: red; font-size: 20px; display:none;"><i class="fa fa-close"></i></span>                     </div>                 </div>             </div>         </div>         <!-- /window -->          <div id="loader_overlay" style="padding-top:10%">             <i class="fa fa-circle-o-notch fa-spin fa-3x fa-fw"></i><br/>         </div>          <!-- scripts/ -->         <script>if (typeof module === 'object') {window.module = module; module = undefined;}</script>         <script src="jquery.min.js" type="text/javascript"></script>         <script>             if (typeof window.jQuery !== 'undefined') {                 window.document.getElementById("loader_overlay").innerHTML += ".";             } else {                 window.document.getElementById("loader_overlay").innerHTML += "x";             }         </script>         <script src="handlebars.min.js" type="text/javascript"></script>         <script>             if (typeof window.Handlebars !== 'undefined') {                 window.document.getElementById("loader_overlay").innerHTML += ".";             } else {                 window.document.getElementById("loader_overlay").innerHTML += "x";             }         </script>         <script src="bridgecommander.js" type="text/javascript"></script>         <script>             if (typeof window.BridgeCommander !== 'undefined') {                 window.document.getElementById("loader_overlay").innerHTML += ".";             } else {                 window.document.getElementById("loader_overlay").innerHTML += "x";             }         </script>         <script src="iban.js" type="text/javascript"></script>         <script>             if (typeof window.IBAN !== 'undefined') {                 window.document.getElementById("loader_overlay").innerHTML += ".";             } else {                 window.document.getElementById("loader_overlay").innerHTML += "x";             }         </script>         <!-- <script src="app.js" type="text/javascript"></script> -->         <script>              // Generated by CoffeeScript 2.0.2             var doValidate;              window.appLoaded = true;             window.document.getElementById("loader_overlay").innerHTML += ".";             BridgeCommander.call("echo", "Before: onload");             window.document.getElementById("loader_overlay").innerHTML += ".";              window.onload = function() {               BridgeCommander.call("echo", "Inside: onload");               document.getElementById("loader_overlay").style.display = 'none';               return $("#validateButton").on("click", doValidate);             };             window.document.getElementById("loader_overlay").innerHTML += ".";             BridgeCommander.call("echo", "After: onload");              doValidate = function() {               var iban, valid;               iban = $("#iban").val();               valid = IBAN.isValid(iban);               if (valid) {                 $("#resultValid").show();                 $("#resultInvalid").hide();                 $("#validateButton").removeClass("invalid").addClass("valid");                 BridgeCommander.call("echo", `Validating: ${iban}, Result: valid`);               } else {                 $("#resultValid").hide();                 $("#resultInvalid").show();                 $("#validateButton").removeClass("valid").addClass("invalid");                 BridgeCommander.call("echo", `Validating: ${iban}, Result: invalid`);               }               setTimeout(function() {                 $("#validateButton").removeClass("valid").removeClass("invalid");                 $("#resultValid").hide();                 return $("#resultInvalid").hide();               }, 3000);               return false;             };             window.document.getElementById("loader_overlay").innerHTML += ".";              if (typeof window.appLoaded !== 'undefined') {                 window.document.getElementById("loader_overlay").innerHTML += ".";             } else {                 window.document.getElementById("loader_overlay").innerHTML += "x";             }         </script>         <script>if (window.module) module = window.module;</script>         <!-- /scripts -->     </body>  </html> 

Important Note: Here (meaning on my Mac - and everyone's Mac with 10.3.1 I've tried this on) everything works fine. When I upload the exact same binary to the App Store for review, I keep getting the same "error" screenshot, signifying none of the code within my last <script></script> block gets executed. (after the window.appLoaded = true part).


What could be going on? I've literally tried anything to debug this (hence, the numerous window.document.getElementById thing, adding dots to make sure everything worked), but still nothing.

As you can see, I'm loading several scripts (which according to my tests load fine), and I also have several pieces of inline JS code (which still work fine). Except for the last one! (which, no matter what, even from an external file, seems to refuse to load...)

Again, I thought about sth being cached, I don't know, but I remind you that it - apparently -- works everywhere apart from the Review team's machine :S

Any idea would be welcome!


P.S. In case something is not clear, please feel free to ask me anything


Update: (28/11/2017) Tried the whole thing with a simple - old-style - WebView (in case it had to do with the WKWebView) and still my app gets rejected. Or to be precise, my app (exact version, same everything) runs fine everywhere, except for the guy that reviews it.

1 Answers

Answers 1

This could be because the browser does not know how to parse the contents of the script tags

<script></script> tags require the type attribute on them most browsers will assume it's the same as the last one but as none of your code containing script tags specifies the type it might not know how to parse them the script support more than javascript for example VBScript to whenever you open a <script> for javascript it should be <script type="text/javascript">

The other problem could be the window.onload I would recommend you change it to the DOMContentLoaded event and use a closure to make sure it executes the code.

More so why are you not loading jQuery in the head tag where it's supposed to be loaded move <script src="jquery.min.js" type="text/javascript"></script> to inside the <head></head>.

Following on from this if you have jQuery why are you mixing jQuery and pure Javascript if you have jQuery use it's smaller code and cleaner

 (function($){      $(function(){          window.appLoaded = true;          $("loader_overlay").append(".");          BridgeCommander.call("echo", "Before: onload");          $("loader_overlay").append(".");           $("loader_overlay").append(".");          BridgeCommander.call("echo", "After: onload");           function doValidate() {              var iban, valid;              iban = $("#iban").val();              valid = IBAN.isValid(iban);              if (valid) {                  $("#resultValid").show();                  $("#resultInvalid").hide();                  $("#validateButton").removeClass("invalid")                                      .addClass("valid");                  BridgeCommander.call("echo", `Validating: ${iban}, Result: valid`);              } else {                  $("#resultValid").hide();                  $("#resultInvalid").show();                  $("#validateButton").removeClass("valid")                                      .addClass("invalid");                  BridgeCommander.call("echo", `Validating: ${iban}, Result: invalid`);              }               setTimeout(function() {                  $("#validateButton").removeClass("valid")                                      .removeClass("invalid");                  $("#resultValid").hide();                  return $("#resultInvalid").hide();              }, 3000);              return false;         };           (function(doValidate) {              BridgeCommander.call("echo", "Inside: onload");              $("loader_overlay").css("display",'none');              return $("#validateButton").on("click", doValidate);          })(doValidate);           window.document.getElementById("loader_overlay").innerHTML += ".";           if (typeof window.appLoaded !== 'undefined') {              window.document.getElementById("loader_overlay").innerHTML += ".";          } else {              window.document.getElementById("loader_overlay").innerHTML += "x";          }          if (window.module){ module = window.module; }     }); }); 

On another note please get rid of all your file loading checks. so all of the following code blocks

if (typeof window.Handlebars !== 'undefined') {     window.document.getElementById("loader_overlay").innerHTML += "."; } else {     window.document.getElementById("loader_overlay").innerHTML += "x"; } 

They are only needed for debugging and you know it's Web Kit if the file loads on one it loads on all. so you don't need these check's they are just using phone processing power and adding work to your app for no good reason. other than to put a . in the overlay...

and again all <script src=... should be inside the <head> tags, in this case, all of your code should be inside the script tags and using jQuery read as my above version does.

How are you testing this App on the Mac are you using the iPhone emulator? or a real iPhone to test i would always recommend the latter. and have you tested in on one of these as you don't seem to say you have, if not get a device registered for testing on your developer account create the keys to test and build a test version then use Safari or chromes remote debugging tools on the WebView and make sure it all works.

Read More

Monday, November 13, 2017

How to detect video in Android WebView with HitTestResult?

Leave a Comment

Like we detect anchor text using hitTestResult.getType() == WebView.HitTestResult.SRC_ANCHOR_TYPE, How can I detect a video playing on Facebook?

I want to know the hitTestResult.GetExtra() for a video file and then search for its valid extension (.mp4) and then download the file.

1 Answers

Answers 1

So as I understand based on what you described you load your FB page in a WebView and want to download .mp4 videos if there is one. This code will do it for you

@Override protected void onCreate(Bundle savedInstanceState) {     super.onCreate(savedInstanceState);     setContentView(R.layout.main);      webView = (WebView)findViewById(R.id.webView);     webView.getSettings().setJavaScriptEnabled(true);     webView.getSettings().setPluginState(WebSettings.PluginState.ON);     webView.getSettings().setBuiltInZoomControls(true);     webView.getSettings().setDisplayZoomControls(true);     webView.getSettings().setUseWideViewPort(true);     webView.getSettings().setLoadWithOverviewMode(true);     webView.addJavascriptInterface(this, "FBDownloader");     webView.setWebViewClient(new WebViewClient() {             @Override             public void onPageFinished(WebView view, String url)             {                 if (swipeLayout.isRefreshing())                 {                     swipeLayout.setRefreshing(false);                 }                  webView.loadUrl("javascript:(function() { "                                 + "var el = document.querySelectorAll('div[data-sigil]');"                                 + "for(var i=0;i<el.length; i++)"                                 + "{"                                 + "var sigil = el[i].dataset.sigil;"                                 + "if(sigil.indexOf('inlineVideo') > -1){"                                 + "delete el[i].dataset.sigil;"                                 + "var jsonData = JSON.parse(el[i].dataset.store);"                                 + "el[i].setAttribute('onClick', 'FBDownloader.processVideo(\"'+jsonData['src']+'\");');"                                 + "}" + "}" + "})()");             }              @Override             public void onLoadResource(WebView view, String url)             {                 webView.loadUrl("javascript:(function prepareVideo() { "                                 + "var el = document.querySelectorAll('div[data-sigil]');"                                 + "for(var i=0;i<el.length; i++)"                                 + "{"                                 + "var sigil = el[i].dataset.sigil;"                                 + "if(sigil.indexOf('inlineVideo') > -1){"                                 + "delete el[i].dataset.sigil;"                                 + "console.log(i);"                                 + "var jsonData = JSON.parse(el[i].dataset.store);"                                 + "el[i].setAttribute('onClick', 'FBDownloader.processVideo(\"'+jsonData['src']+'\",\"'+jsonData['videoID']+'\");');"                                 + "}" + "}" + "})()");                 webView.loadUrl("javascript:( window.onload=prepareVideo;"                                 + ")()");             }         });      CookieSyncManager.createInstance(this);     CookieManager cookieManager = CookieManager.getInstance();     cookieManager.setAcceptCookie(true);     CookieSyncManager.getInstance().startSync();      webView.loadUrl(target_url); }  @JavascriptInterface public void processVideo(final String vidData, final String vidID) {     try     {         String mBaseFolderPath = android.os.Environment             .getExternalStorageDirectory()             + File.separator             + "FacebookVideos" + File.separator;         if (!new File(mBaseFolderPath).exists())         {             new File(mBaseFolderPath).mkdir();         }         String mFilePath = "file://" + mBaseFolderPath + "/" + vidID + ".mp4";          Uri downloadUri = Uri.parse(vidData);         DownloadManager.Request req = new DownloadManager.Request(downloadUri);         req.setDestinationUri(Uri.parse(mFilePath));         req.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);         DownloadManager dm = (DownloadManager) getSystemService(getApplicationContext().DOWNLOAD_SERVICE);         dm.enqueue(req);         Toast.makeText(this, "Download Started", Toast.LENGTH_LONG).show();     }     catch (Exception e)     {         Toast.makeText(this, "Download Failed: " + e.toString(), Toast.LENGTH_LONG).show();     } } 
Read More

Sunday, November 12, 2017

Redirection to a mobile app from the webview of the app itself in React Native

Leave a Comment

I'm building an android application which requires authentication from an external auth provider.So I'm using react-native-oauth package to handle this.

The redirect_uri defined is a deep link which should ideally open my app itself after successful authentication.But the WebView seems to not handle this redirection and I'm getting response as 404-page not found.

This is the service that I have written to handle the auth:

    const manager = new OAuthManager('<app_name>')      manager.addProvider({          'provider': {                   auth_version: '2.0',                    authorize_url:'<auth-url>',                   access_token_url: '<auth-url>/token',                   callback_url: 'http://localhost/provider',          }     });      manager.configure({        provider: {            client_id: '<id>',            client_secret: '<secret>',            redirect_uri: '<redirect-uri>' //DEEP LINK HERE       }     });    module.exports = {       authManager: () => {       manager.authorize('<provider>')                         .then(resp => console.log(resp))                         .catch(err => console.log(err));                         }    } 

Also I have defined my intent-filter as specified in the Android docs on how to declare the deep links for your apps.The deep link works fine when opened with Linking.openURL() from the app components.

Any help in this is much appreciated.

2 Answers

Answers 1

You can't directly set redirect_uri to your mobile app ( because most auth providers doesn't support custom OAuth scheme ).

But you can create some web page that will accept redirect from OAuth providers and will open your app ( and send all redirect params, like token ).

For example you create page https://example.com/oauth/, and set callback_url to https://example.com/oauth/XXXXX_provider, so when user will be redirected to page https://example.com/oauth/XXXXX_provider&token=xxx it will open you app using appName://example/oauth/google?token=xxx

You can handle appName://example/oauth/google?token=xxx using Deeplink ( it will open your mobile app when it is installed on device )

Example of page to handle redirects:

<html><head></head><body>  <p>Please wait while we redirect you to Your APP NAME...</p>  <p><a href="javascript:redirectToApp()">Open appname</a></p>  <script>    var redirectToApp = function() {      var scheme = "appnameapp";      var openURL = "appname" + window.location.pathname + window.location.search + window.location.hash;      var iOS = /iPad|iPhone|iPod/.test(navigator.userAgent);      var Android = /Android/.test(navigator.userAgent);      var newLocation;      if (iOS) {        newLocation = scheme + ":" + openURL;      } else if (Android) {        newLocation = "intent://" + openURL + "#Intent;scheme=" + scheme + ";package=com.appnameapp;end";      } else {        newLocation = scheme + "://" + openURL;      }      console.log(newLocation)      window.location.replace(newLocation);    }    window.onload = redirectToApp;  </script>      </body></html>

Answers 2

WebView by default doesn't share cookies/session data with Safari/Chrome. So it is not ideal for login flow since it doesn't use the existing logged in session in Chrome/Safari.

Expo provides a WebBrowser api that will open Safari/Chrome instead of webview. Note that it opens Safari/Chrome inside the app, instead of redirecting you the browser using Linking. So users always have a button in the browser to get back to your app.

You can use WebBrowser.openAuthSessionAsync(url) to open a secure session which shares cookie/session info with the native browser in the device.

Expo also provides another api called AuthSession that simplifies a lot of boilerplate and provides a simple api.

Read More

Sunday, November 5, 2017

webview MediaPlayer: info/warning (702, 0)

Leave a Comment

I am trying to load an HTML file in webview(e.g. mWebView.loadUrl("file://..player.html) which plays an html5 video, then displays an image for few seconds, then goes back to video and repeats this cycle in a nonstop loop. Every thing goes fine for the first few hundreds of the loop run, however after some random iterations the webview starts to act out, stops playing the video and displays these messages blew. Any clue what could be wrong?

The last status of the video before the pkaying stops is "durationchange" or "canplaythrough"

10-26 20:23:49.864  5168  5334 W MediaPlayer: info/warning (702, 0) 10-26 20:23:49.864  5168  5334 W MediaPlayer: info/warning (702, 0) 10-26 20:23:49.864  5168  5334 W MediaPlayer: info/warning (702, 0) 10-26 20:23:49.864  5168  5334 W MediaPlayer: info/warning (702, 0) 10-26 20:23:49.864  5168  5334 W MediaPlayer: info/warning (702, 0) 10-26 20:23:49.864  5168  5334 W MediaPlayer: info/warning (702, 0) 10-26 20:23:49.864  5168  5334 W MediaPlayer: info/warning (702, 0) 10-26 20:23:49.864  5168  5334 W MediaPlayer: info/warning (702, 0) 10-26 20:23:49.864  5168  5334 W MediaPlayer: info/warning (702, 0) 10-26 20:23:49.864  5168  5334 W MediaPlayer: info/warning (702, 0) 10-26 20:23:49.864  5168  5334 W MediaPlayer: info/warning (702, 0) 10-26 20:23:49.864  5168  5334 W MediaPlayer: info/warning (702, 0) 

I already looked into Android MediaPlayer : info/warning (703, 0),info/warning (702, 0),info/warning (701, 0),ProtocolException when try to seek from a random position

but did not help! its is so strange tha for the first few hundres times

0 Answers

Read More

Friday, September 29, 2017

save a web view content as pdf file

Leave a Comment

Notice: I working with swift 4 for osx. I would like to generate a pdf file from a WebView.

At the moment my WebView load a html-string and show this successfully. If I press a button, the print panel will open and is ready to print my WebView content in the correct format.

This is my print code:

var webView = WebView() var htmlString = "MY HTML STRING"  override func viewDidLoad() {     webView.mainFrame.loadHTMLString(htmlString, baseURL: nil) }  func webView(_ sender: WebView!, didFinishLoadFor frame: WebFrame!) {      let printInfo = NSPrintInfo.shared     printInfo.paperSize = NSMakeSize(595.22, 841.85)     printInfo.isHorizontallyCentered = true     printInfo.isVerticallyCentered = true     printInfo.orientation = .portrait     printInfo.topMargin = 50     printInfo.rightMargin = 0     printInfo.bottomMargin = 50     printInfo.leftMargin = 0     printInfo.verticalPagination = .autoPagination     printInfo.horizontalPagination = .fitPagination     //webView.mainFrame.frameView.printOperation(with: printInfo).run()      let printOp: NSPrintOperation = NSPrintOperation(view: webView.mainFrame.frameView.documentView, printInfo: printInfo)     printOp.showsPrintPanel = true     printOp.showsProgressPanel = false     printOp.run()  } 

enter image description here

Now I would like to have another button, which save the content directly as a pdf file.

I tried this:

let pdfData = webView.mainFrame.frameView.documentView.dataWithPDF(inside: webView.mainFrame.frameView.documentView.frame) let document = PDFDocument(data: pdfData) let fileURL = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false).appendingPathComponent("myPDF.pdf") document?.write(to: fileURL) 

But the result of my pdf looks horrible:

enter image description here

Have anybody an idea?

UPDATE This is a part of my web view result:

enter image description here

and that is the result of my print preview / pdf file /the color is missing, but now everywhere. the "logo"(picture) will show with color: enter image description here

1 Answers

Answers 1

The problem is that dataWithPDF uses the view's current frame to decide how wide the generated PDF should be. Since your WebView's frame in your app is probably skinnier than an 8.5/11" page, you're getting a PDF that is inadequately wide. You could adjust the WebView's frame to the right size, make the PDF, and then adjust it back, or you could create a new WebView, render it offscreen, set it to the appropriate size, and create the PDF. That's a bit of a pain in the backside, though. Wouldn't it be great if there were a way to programatically do what the "PDF" button in the Print dialog does, since the print system handles all this stuff for you automatically?

Well, turns out you can! But you have to dive into the poorly-documented world of Core Printing.

func makePDF(at url: URL, for webView: WebView, printInfo: NSPrintInfo) throws {     webView.preferences.shouldPrintBackgrounds = true      guard let printOp = webView.mainFrame.frameView.printOperation(with: printInfo) else {         throw MyPrintError.couldntGetPrintOperation // or something like this     }      let session = PMPrintSession(printOp.printInfo.pmPrintSession())     let settings = PMPrintSettings(printOp.printInfo.pmPrintSettings())      if PMSessionSetDestination(session,                                settings,                                PMDestinationType(kPMDestinationFile),                                kPMDocumentFormatPDF as CFString,                                url as CFURL) != noErr {         throw MyPrintError.couldntSetDestination // or something like this     }      printOp.showsPrintPanel = false     printOp.run() } 

The key is the PMSessionSetDestination call, which allows us to configure the print session to print to a PDF instead of to an actual printer. Then we just tell NSPrintOperation not to show the print panel, run the operation, and presto! PDF printed.

Read More

Monday, September 11, 2017

Android WebView Video after closing fullscreen view, webview auto scrolls

Leave a Comment

I am using WebView to display a webpage having text as well as video content.

It loads & display video correctly as expected.

But when I go to full screen view of video ( I implemeted full screen video view as given here ) and then come back to WebView, WebView autoscroll in some amount.

How can I fix that?

Please suggest some idea/link.

0 Answers

Read More

Friday, August 18, 2017

Getting Bitmap from WebView generates OutOfMemory crash

Leave a Comment

I have a custom WebView and I want to get a bitmap of its content (offscreen included). I used this code, which I got from here:

 public static Bitmap getBitmapFromWebviewV2(WebView webView) {     webView.measure(View.MeasureSpec.makeMeasureSpec(         View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED),         View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));     webView.layout(0, 0, webView.getMeasuredWidth(),             webView.getMeasuredHeight());     webView.setDrawingCacheEnabled(true);     webView.buildDrawingCache();     Bitmap bm = Bitmap.createBitmap(webView.getMeasuredWidth(),             webView.getMeasuredHeight(), Bitmap.Config.ARGB_8888);      Canvas bigcanvas = new Canvas(bm);     Paint paint = new Paint();     int iHeight = bm.getHeight();     bigcanvas.drawBitmap(bm, 0, iHeight, paint);     webView.draw(bigcanvas);     return bm; } 

It works fine up to the point when I zoom in a lot, in which case I get OutOfMemory Crash. I tested this with the same picture (slightly zoomed and zoomed to the max) and it behaves in the same way I mentioned above.

I tried to counter this by adding

while(webView.canZoomOut()){       webView.zoomOut(); } 

at the start, but it doesn't help at all.

3 Answers

Answers 1

Okay, I've cracked this one meself. The problem indeed was in the fact that the function returned the Bitmap waay before the zooming out procedure was over, so I had to delay it.

I incorporated

Handler handler = new Handler();         handler.postDelayed(new Runnable() {             @Override             public void run() {                 //bulk of my code             }         }, 1000); 

which forced to change the structure of the function from public Bitmap to public void. Here's directly related thread. Despite some minor tweaks I still need to fix, the approach works like a charm

Answers 2

Quick fix:-

Set android:largeHeap="true" in your AndroidManifest.xml file.

<application     android:name="yourapplication"     android:allowBackup="true"     android:icon="@mipmap/ic_launcher_rounded"     android:label="@string/app_name"     android:largeHeap="true"     android:roundIcon="@mipmap/ic_launcher_rounded"     android:supportsRtl="true"     android:theme="@style/AppTheme"> 

Gud luck :)

Answers 3

You write code to capture Bitmap from Webview but code which creates outOfmemmory you should write onces.

webView.measure(View.MeasureSpec.makeMeasureSpec(             View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED),             View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));  Bitmap bm = Bitmap.createBitmap(webView.getMeasuredWidth(),                 webView.getMeasuredHeight(), Bitmap.Config.ARGB_8888); 

So above code should be written once and create Bitmap object Global and check if it's not null then over right new drawing cache in Bitmap.

Because each time when you create new Bitmap it consumes a lot of memory.

Read More

Tuesday, August 8, 2017

How open link in safari mobile app from webview

Leave a Comment

There are many topics of this here, but they all need native code interaction to work.

In my case, it is necessary to be able to do it directly from the url, without any interaction with my mobile app.

I tried:

<a href="safari://google.com" target="_blank">Open Google in Safari</a>

and

<a href="webkit://google.com" target="_blank">Open</a>

and based in this post.

<script>     $(document).on('click', 'a[target="_blank"]', function (ev) {       var url;        ev.preventDefault();       url = $(this).attr('href');       window.open(url, '_system');     });   </script> 

but nothing works.

Anyone have any idea how to fix this?

1 Answers

Answers 1

If this is running in safari it should comply with safari async call restrictions regarding popups as explained here.

You should fix your code so that the window open will be outside the function, Something like that:

    <script>     var windowReference = window.open();      $(document).on('click', 'a[target="_blank"]', function (ev) {       var url;        ev.preventDefault();       url = $(this).attr('href');       windowReference.location = url;     });   </script> 
Read More

Thursday, August 3, 2017

Play local Video in webview

Leave a Comment

I want to play local videos in crosswalk webview. I'm getting the video path from an intent opening my activity, so it could be stored internally or on sd card.

Using this url file:///storage/emulated/0/Download/movies/movie.mp4 i get Failed to load resource: net::ERR_ACCESS_DENIED.

Using input file dialog with URL.createObjectURL(file); it works. But because i know the path, i dont want to select it again manually. Setting the value of input file is forbidden.

Creating a url using the path is also not possible, because it needs file or blob.

Because of possible big filesize its not possible to temporarily copy it to sd card.

This gives me file not found error:

@Override     public WebResourceResponse shouldInterceptLoadRequest(XWalkView view,                                                           String url) {         if(url.contains("file:///storage")){             try {                 return new WebResourceResponse("video/*", "UTF-8", new FileInputStream(url));             } catch (FileNotFoundException e) {                 e.printStackTrace();             }         }             return super.shouldInterceptLoadRequest(view, url);     } 

also i have defined <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

other questions on stackoverflow asking for accessing assets, so i created this new question

2 Answers

Answers 1

To access local files on android devices running marshmellow or above, you are required to check the permission at runtime before trying to access the file. If you don't, it will break

Here is a tutorial where it is implemented, specifically reading of files https://www.androidhive.info/2016/11/android-working-marshmallow-m-runtime-permissions/

Depending on the source of the file, I would recommend you not checking before playing but checking just before the entry point. For example, if you are trying to select a media from gallary, or a file from the file manager, just before you create the file intent picker, you check for the write permission, you then proceed as shown below

    @Override     public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {         super.onRequestPermissionsResult(requestCode, permissions, grantResults);         if (requestCode == EXTERNAL_STORAGE_PERMISSION_CONSTANT) {             if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {                //The External Storage Write Permission is granted to you... Continue your left job...                proceedAfterPermission();            } else {                //request again for permission or assume permission denied and alert the user            }        }     } 

You should still study the link, its pretty easy to implement. Hopefully you'll find this helpful

Answers 2

The problem might be in accessing video file from External storage also make sure you have given read/write Run time permission . Here you can find your solution here and this

Read More

Tuesday, August 1, 2017

Show Prompt to know the location

Leave a Comment

I am using Xamarin WebView controller to display a web site (in both iOS/Android). The web site's home page prompts to access the device location. But that prompt is not showing when I have this website on a WebView (from the App). When I open this site on the browser, from the same mobile device it shows the message box. I am just wondering if it is possible to have such prompts on Xamarin WebView?

Here is an example prompt.

enter image description here

This is all I have in the Xamarin app.

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"              xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"              xmlns:local="clr-namespace:nCollar"              x:Class="nCollar.MainPage">     <ContentPage.Padding>         <OnPlatform x:TypeArguments="Thickness">             <OnPlatform.iOS>0,20,0,0</OnPlatform.iOS>             <OnPlatform.Android>0,0,0,0</OnPlatform.Android>             <OnPlatform.WinPhone>0,0,0,0</OnPlatform.WinPhone>         </OnPlatform>     </ContentPage.Padding>      <WebView x:Name="webView"                  Grid.Row="0"                  VerticalOptions="FillAndExpand"                   Source="https://www.ncollar.com.au/"/>  </ContentPage> 

UPDATE 1

Android

I've tried the solution mentioned in this post, but still it doesn't show the prompt.

WebViewRenderer.cs

using Android.Webkit; using Xamarin.Forms.Platform.Android;  [assembly: Xamarin.Forms.ExportRenderer(typeof(TestApp.Controls.WebView), typeof(TestApp.Droid.Renderers.WebViewRenderer))] namespace TestApp.Droid.Renderers {     public class WebViewRenderer : Xamarin.Forms.Platform.Android.WebViewRenderer     {         protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.WebView> e)         {             base.OnElementChanged(e);              if (this.Control == null)             {                 return;             }              var webView = this.Element as TestApp.Controls.WebView;             if (webView == null)             {                 return;             }              // webView. ings.JavaScriptEnabled = true;             this.Control.Settings.DomStorageEnabled = true;             this.Control.Settings.DisplayZoomControls = true;             this.Control.Settings.BuiltInZoomControls = true;             this.Control.Settings.SetGeolocationEnabled(true);             this.Control.Settings.JavaScriptCanOpenWindowsAutomatically = true;              this.Control.SetWebViewClient(new GeoWebViewClient());             this.Control.SetWebChromeClient(new GeoWebChromeClient());         }     }      public class GeoWebChromeClient : WebChromeClient     {         public override void OnGeolocationPermissionsShowPrompt(string origin, GeolocationPermissions.ICallback callback)         {             callback.Invoke(origin, true, false);         }     }      public class GeoWebViewClient : WebViewClient     {         public override bool ShouldOverrideUrlLoading(WebView view, string url)         {             view.LoadUrl(url);             return true;         }     } } 

Manifest

<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android">     <uses-sdk android:minSdkVersion="15" />   <uses-permission android:name="android.permission.INTERNET" />   <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />     <application android:label="TestApp.Android"></application> </manifest> 

iOS

Tried NSLocationWhenInUseUsageDescription in the plist file, but no difference.

Example App that does a similar thing

enter image description here

3 Answers

Answers 1

In case of Android - you should be able to resolve this by adding a platform-specific renderer for WebView and implement the permission handling by adding a custom WebChromeClient.

In case of iOS - you need to add NSLocationWhenInUseUsageDescription description in your info plist

Answers 2

On Android:

According to Xamarin docs OnGeolocationPermissionsShowPrompt is used to "Notify the host application that web content from the specified origin is attempting to use the Geolocation API, but no permission state is currently set for that origin. The host application should invoke the specified callback with the desired permission state." As you can see there is nothing said about confirmation dialog. If you call "callback" without any prompt you are setting the result (I tested, permission is granted after callback is called). You should implement confirmation dialog yourself. Note: It will set permission only if you have LOCATION_ACCESS in your manifest, otherwise it will not.

On iOS:

I don't know. :-) but probably the similar thing happens there.

I wouldn't even bother to capture those requests from browser. There are "normal" methods to ask user for location permissions if your app needs them.

Answers 3

But that prompt is not showing when I have this website on a WebView (from the App).

If I got it right, you're wrapping this in an app. That's not the expected user experience from a mobile app. your app should use the platform(e.g iOS,Android) location permissions in order to get the user approval.

Xamarin will let you access Location on each platform quite differently. If the Xamarin app has access to location than the webview should inherit these permissions. So it might worth trying this recipe and try accsing location before opening the webview itself

Read More