how to add Desktop Version of Website in Flutter app? - android

i need to show desktop version of website in my app. for me it shows the mobile version of app:
code:
import 'package:flutter/material.dart';
import 'package:flutter_webview_plugin/flutter_webview_plugin.dart';
import './landing_page.dart';
class ComicsPage extends StatefulWidget {
#override
_ComicsPageState createState() => _ComicsPageState();
}
class _ComicsPageState extends State<ComicsPage> {
TextEditingController controller = TextEditingController();
FlutterWebviewPlugin flutterWebviewPlugin = FlutterWebviewPlugin();
var urlString = "https://avengers.marvelhq.com/comics";
launchUrl() {
setState(() {
urlString = controller.text;
flutterWebviewPlugin.reloadUrl(urlString);
});
}
#override
void initState() {
super.initState();
flutterWebviewPlugin.onStateChanged.listen((WebViewStateChanged wvs) {
print(wvs.type);
});
}
#override
Widget build(BuildContext context) {
String newUA= "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:40.0) Gecko/20100101
Firefox/40.1";
return WebviewScaffold(
appBar: AppBar(
actions: <Widget>[
IconButton(
icon: Icon(Icons.cancel,size: 45.0),
onPressed: () => Navigator.of(context).pushAndRemoveUntil(new
MaterialPageRoute(builder: (BuildContext context) => new LandingPage()),
(Route route) => route == null),
)
],
title: const Text('Marvel Comics'),
),
url: urlString,
withZoom: true,
withJavascript: true,
withLocalStorage: true,
scrollBar: true,
enableAppScheme: true,
userAgent: newUA,
clearCookies: false,
clearCache: false,
);
}
}
i need to view like this sample image
especially for this site: click here
i tried to change useragent to desktop version(Mozilla/5.0 (Windows NT 6.1; WOW64; rv:40.0) Gecko/20100101 Firefox/40.1). it not works.. give me solution.

i know this late answer but maybe someone will need it
BTW i also face this problem before in flutter
after do this trick it was work for me
just try eval this code JavaScript after your page is Loaded
like this
//to load desktop mode
String js =
"document.querySelector('meta[name=\"viewport\"]').setAttribute('content', 'width=1024px, initial-scale=' + (document.documentElement.clientWidth / 1024));";
#override
Widget build(BuildContext context) {
final flutterWebViewPlugin = new FlutterWebviewPlugin();
flutterWebViewPlugin.onProgressChanged.listen((event) {
debugPrint("Progress $event");
//this will make show in desktop mode
flutterWebViewPlugin.evalJavascript(js);
});
return WebviewScaffold(
appBar: AppBar(
title: Text("Desktop Mode"),
),
url: "My Url",
withJavascript: true,
useWideViewPort: true,
displayZoomControls: false,
scrollBar: true,
withZoom: true,
);
}
Link Of WebView Plugin here

Change the user agent parameter from null to the value mentioned below
WebView(
userAgent: "Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.4) Gecko/20100101 Firefox/4.0",
initialUrl: html,
javascriptMode: JavascriptMode.unrestricted,
onWebViewCreated: (WebViewController webViewController) {
_controller.complete(webViewController);
},

Related

Whatsapp web Desktop mode in flutter

I want to open Whatsapp Web Desktop mode in my flutter app
As shown in picture
Required Result
I am used webview_flutter webview_flutter_plus packages but both results same.
my initial url is
https://web.whatsapp.com
The code i am using are as follow
class WhatsAppWebScreen extends StatefulWidget {
WhatsAppWebScreen({Key? key}) : super(key: key);
// late Completer<WebViewController> controller;
#override
State<WhatsAppWebScreen> createState() => _WhatsAppWebScreenState();
}
class _WhatsAppWebScreenState extends State<WhatsAppWebScreen> {
#override
Widget build(BuildContext context) {
return Scaffold(
drawer: const DrawerWidget(),
appBar: AppBar(
title: const Text("WhatsAppWeb"),
backgroundColor: Color(0xFF128D7E),
),
body: SingleChildScrollView(
child: Container(
height: 80.h,
child: WebViewPlus(
initialUrl: 'https://web.whatsapp.com',
userAgent:
"Mozilla/5.0 (Macintosh; Intel Mac OS X 11_2_1) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.0.3 Safari/605.1.15",
javascriptMode: JavascriptMode.unrestricted,
),
),
),
);
}
}
Every Time i run this code the url redirects into
www.whatsapp.com
and results like this
enter image description here
I try many different user agents strings but the same result.
I used navigationdelegate parameter to prevent redirection of url. but then it shows blank screen
navigationDelegate: (request) {
if (request.url.startsWith('https://www.whatsapp.com/')) {
print('blocking navigation to $request}');
return NavigationDecision.prevent;
}
print('allowing navigation to $request');
return NavigationDecision.navigate;
},
onWebViewCreated: (webViewController) {
_controller.complete(webViewController);
},
How can i open whatsapp web desktop mode in my flutter app?
WebView(
initialUrl: 'https://web.whatsapp.com',
userAgent:"Mozilla/5.0 (Macintosh; Intel Mac OS X 11_2_1) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.0.3 Safari/605.1.15",
javascriptMode: JavascriptMode.unrestricted,
),

i am facing flutter webview issue

I am new in a flutter. I m facing an issue in flutter_webview here is my code IDK what's wrong with it. I write this code with the help of StackOverflow and an official plugin. my HTML files working fine
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:webview_flutter/webview_flutter.dart';
class Licences extends StatefulWidget {
#override
_LicencesState createState() => _LicencesState();
}
class _LicencesState extends State<Licences> {
WebViewController webViewController;
String filePath = 'files/PrivacyPolicy.html';
loadHtml() async {
String data = await rootBundle.loadString(filePath);
webViewController.loadUrl(Uri.dataFromString(data,
mimeType: 'text/html', encoding: Encoding.getByName('utf-8'))
.toString());
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Open-Source Licences'),
),
body: Builder(builder: (BuildContext context) {
return WebView(
initialUrl: '',
javascriptMode: JavascriptMode.unrestricted,
onWebViewCreated: (WebViewController controller) {
webViewController = controller;
loadHtml();
},
);
}),
);
}
}

Flutter webview intercept and add headers to all requests

Using the webview_flutter package i could load my website and add session cookies to the initial URL.
_controller.future.then((controller) {
_webViewController = controller;
Map<String, String> header = {'Cookie': 'ci_session=${widget.sessionId}'};
_webViewController.loadUrl('https://xxxx.com', headers: header);
});
In order to keep the session going i need to add the same header for all requests not just for the initial one.
Is there any way to intercept all requests and modify them by adding headers to them?
the closest thing i found was navigationDelegate but it only returns a NavigationDecision which isn't useful in my case.
You can use my plugin flutter_inappwebview, which is a Flutter plugin that allows you to add inline WebViews or open an in-app browser window and has a lot of events, methods, and options to control WebViews.
If you need to add custom headers for each request, you can use the shouldOverrideUrlLoading event (you need to enable it using useShouldOverrideUrlLoading: true option).
Instead, if you need to add cookies to your WebView, you can just use the CookieManager class (CookieManager.setCookie method to set a cookie).
Here is an example that set a cookie (named ci_session) in your WebView and also set a custom header (named My-Custom-Header) for each request:
import 'dart:async';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';
Future main() async {
WidgetsFlutterBinding.ensureInitialized();
runApp(MyApp());
}
class MyApp extends StatefulWidget {
#override
_MyAppState createState() => new _MyAppState();
}
class _MyAppState extends State<MyApp> {
InAppWebViewController webView;
CookieManager _cookieManager = CookieManager.instance();
#override
void initState() {
super.initState();
_cookieManager.setCookie(
url: "https://github.com/",
name: "ci_session",
value: "54th5hfdcfg34",
domain: ".github.com",
isSecure: true,
);
}
#override
void dispose() {
super.dispose();
}
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('InAppWebView Example'),
),
body: Container(
child: Column(children: <Widget>[
Expanded(
child: InAppWebView(
initialUrl: "https://github.com/",
initialHeaders: {'My-Custom-Header': 'custom_value=564hgf34'},
initialOptions: InAppWebViewGroupOptions(
crossPlatform: InAppWebViewOptions(
debuggingEnabled: true,
useShouldOverrideUrlLoading: true
),
),
onWebViewCreated: (InAppWebViewController controller) {
webView = controller;
},
onLoadStart: (InAppWebViewController controller, String url) {},
onLoadStop: (InAppWebViewController controller, String url) async {
List<Cookie> cookies = await _cookieManager.getCookies(url: url);
cookies.forEach((cookie) {
print(cookie.name + " " + cookie.value);
});
},
shouldOverrideUrlLoading: (controller, shouldOverrideUrlLoadingRequest) async {
print("URL: ${shouldOverrideUrlLoadingRequest.url}");
if (Platform.isAndroid || shouldOverrideUrlLoadingRequest.iosWKNavigationType == IOSWKNavigationType.LINK_ACTIVATED) {
controller.loadUrl(url: shouldOverrideUrlLoadingRequest.url, headers: {
'My-Custom-Header': 'custom_value=564hgf34'
});
return ShouldOverrideUrlLoadingAction.CANCEL;
}
return ShouldOverrideUrlLoadingAction.ALLOW;
},
))
])),
),
);
}
}
in flutter_webview case
onWebViewCreated: (WebViewController webViewController) {
this.webViewController = webViewController;
},
onPageStarted: (url) {
webViewController.loadUrl(url, headers: headers);
},
use this

Not able to view web page in webview on Android emulator

I am trying to run the WebView Sample of Flutter in android emulator which is provided by Android studio itself. Now the problem I am facing is while I am running the sample I am not able to view the web page in WebView itself.
When the app runs for the first time it asks me to open the initialUrl into either into the chrome or web browser see below screenshots.
However, when I run the same sample in my mobile device it works fine and I can see the web page insdie WebView
Code
class _WikipediaExplorerState extends State<WikipediaExplorer> {
Completer<WebViewController> _controller = Completer<WebViewController>();
final Set<String> _favorites = Set<String>();
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Wikipedia Explorer'),
// This drop down menu demonstrates that Flutter widgets can be shown over the web view.
actions: <Widget>[
NavigationControls(_controller.future),
Menu(_controller.future, () => _favorites),
],
),
body: WebView(
initialUrl: 'https://en.wikipedia.org/wiki/Kraken',
onWebViewCreated: (WebViewController webViewController) {
_controller.complete(webViewController);
},
),
floatingActionButton: _bookmarkButton(),
);
}
_bookmarkButton() {
return FutureBuilder<WebViewController>(
future: _controller.future,
builder:
(BuildContext context, AsyncSnapshot<WebViewController> controller) {
if (controller.hasData) {
return FloatingActionButton(
onPressed: () async {
var url = await controller.data.currentUrl();
_favorites.add(url);
Scaffold.of(context).showSnackBar(
SnackBar(content: Text('Saved $url for later reading.')),
);
},
child: Icon(Icons.favorite),
);
}
return Container();
},
);
}
}

Flutter Webview change webpage is not available

I wanna change the "Webpage not available", in my WebView application, if the user doesn't have internet.
I read the documentation, and try some another puglins
import 'package:webview_flutter/webview_flutter.dart';
[...]
class _MyHomePageState extends State<MyHomePage> {
#override
Widget build(BuildContext context) {
return Scaffold(
body: const WebView(
initialUrl: 'https://google.com',
javascriptMode: JavascriptMode.unrestricted,
),
);
}
}
You can try my plugin flutter_inappwebview. It has events to manage errors while the WebView is loading an url (onLoadError event) and when it receives HTTP errors, such as 403, 404, etc (onLoadHttpError event).
Full example with working code that loads a custom error page if the user doesn't have internet connection:
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';
Future main() async {
runApp(new MyApp());
}
class MyApp extends StatefulWidget {
#override
_MyAppState createState() => new _MyAppState();
}
class _MyAppState extends State<MyApp> {
#override
void initState() {
super.initState();
}
#override
void dispose() {
super.dispose();
}
#override
Widget build(BuildContext context) {
return MaterialApp(
home: InAppWebViewPage()
);
}
}
class InAppWebViewPage extends StatefulWidget {
#override
_InAppWebViewPageState createState() => new _InAppWebViewPageState();
}
class _InAppWebViewPageState extends State<InAppWebViewPage> {
InAppWebViewController webView;
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("InAppWebView")
),
body: Container(
child: Column(children: <Widget>[
Expanded(
child: Container(
child: InAppWebView(
initialUrl: "https://flutter.dev/",
initialHeaders: {},
initialOptions: InAppWebViewWidgetOptions(
inAppWebViewOptions: InAppWebViewOptions(
debuggingEnabled: true,
),
),
onWebViewCreated: (InAppWebViewController controller) {
webView = controller;
},
onLoadStart: (InAppWebViewController controller, String url) {
},
onLoadStop: (InAppWebViewController controller, String url) {
},
onLoadError: (InAppWebViewController controller, String url, int code, String message) async {
print("error $url: $code, $message");
var tRexHtml = await controller.getTRexRunnerHtml();
var tRexCss = await controller.getTRexRunnerCss();
controller.loadData(data: """
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0,maximum-scale=1.0, user-scalable=no">
<style>$tRexCss</style>
</head>
<body>
$tRexHtml
<p>
URL $url failed to load.
</p>
<p>
Error: $code, $message
</p>
</body>
</html>
""");
},
onLoadHttpError: (InAppWebViewController controller, String url, int statusCode, String description) async {
print("HTTP error $url: $statusCode, $description");
},
),
),
),
]))
);
}
}
The result is:
This example loads directly an html source, but you can load an html file from the assets folder or an url.
Just for fun: my plugin includes the javascript and css code of the Google Chrome t-rex game!
Just Add onWebResourceError method to your Webview.
WebView(
onWebResourceError: (WebResourceError webviewerrr) {
print("Handle your Error Page here");
},
initialUrl: "your url"
javascriptMode: JavascriptMode.unrestricted,
onPageFinished: (String url) {
print('Page finished loading:');
},
);

Categories

Resources