Forwarded URL renders the webpage in half the height as normal for a Flutter Web app hosted in Firebase - html

I have a firebase hosted Flutter Web application which is a game. Since the URL for the Firebase hosted site (https://jw-daily.web.app) is difficult to remember for users, I bought a domain name (joinedwords.com) and redirected the URL to the firebase hosted site.
Problem is that when I type the domain URL i.e. joinedwords.com, the website renders in only half the height like below:
However, if I type the original URL (https://jw-daily.web.app) in the browser, the webpage renders in full like below:
All that I have done is with my domain provider, I have set a forward with masking of joinedwords.com => https://jw-daily.web.app/
I looked up all the other solutions around why a webpage is rendering in half. However most of them are asking to make changes to the code and I don't want to do that since the original URL is working fine. Incidentally this issue is happening only on mobile browsers and not happening on desktop. In desktop, the website renders correctly regardless of which URL is typed.
Please suggest if you are aware of how we can solve this problem. Here is my index.html file.
<!DOCTYPE html>
<html prefix="og: http://ogp.me/ns#">
<head>
<!--
If you are serving your web app in a path other than the root, change the
href value below to reflect the base path you are serving from.
The path provided below has to start and end with a slash "/" in order for
it to work correctly.
For more details:
* https://developer.mozilla.org/en-US/docs/Web/HTML/Element/base
-->
<base href="/">
<meta charset="UTF-8">
<meta content="IE=Edge" http-equiv="X-UA-Compatible">
<meta name="description" content="A Daily Word Game">
<meta image="" />
<meta property="og:image:url" content="https://s3.us-east-2.amazonaws.com/joint.words/joined-xxx.png"
property="og:image:secure_url" content="https://s3.us-east-2.amazonaws.com/joint.words/joined-xxx.png"
property ="og:image:alt" content="Joined Words Logo"
property="og:image:type" content="image/png"
/>
<!--
property="og:image:width" content="100"
property="og:image:height" content="100"
-->
<!-- iOS meta tags & icons -->
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black">
<meta name="apple-mobile-web-app-title" content="Joined Words">
<link rel="apple-touch-icon" href="https://s3.us-east-2.amazonaws.com/joint.words/joined-256.png">
<!-- Favicon -->
<link rel="shortcut icon" href="favicon.png" type="image/x-icon">
<link rel="icon" href="favicon.png" type="image/x-icon">
<title>Joined Words</title>
<link rel="manifest" href="manifest.json">
<meta name="google-site-verification" content="XXXXXXXXX-XXXXXX" />
/>
<!-- Global site tag (gtag.js) - Google Ads: xxxxxxxxx -->
<script async src="https://www.googletagmanager.com/gtag/js?id=AW-xxxxxxxxxxx"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'AW-xxxxxxxxxxx');
</script>
<!-- Event snippet for Website traffic conversion page -->
<script>
gtag('event', 'conversion', {'send_to': 'xxxxxxxxxxxxxxxxxxx'});
</script>
</head>
<body>
<!-- This script installs service_worker.js to provide PWA functionality to
application. For more information, see:
https://developers.google.com/web/fundamentals/primers/service-workers -->
<script>
var serviceWorkerVersion = null;
var scriptLoaded = false;
function loadMainDartJs() {
if (scriptLoaded) {
return;
}
scriptLoaded = true;
var scriptTag = document.createElement('script');
scriptTag.src = 'main.dart.js?version=1';
scriptTag.type = 'application/javascript';
document.body.append(scriptTag);
}
if ('serviceWorker' in navigator) {
// Service workers are supported. Use them.
window.addEventListener('load', function () {
// Wait for registration to finish before dropping the <script> tag.
// Otherwise, the browser will load the script multiple times,
// potentially different versions.
var serviceWorkerUrl = 'flutter_service_worker.js?v=' + serviceWorkerVersion;
navigator.serviceWorker.register(serviceWorkerUrl)
.then((reg) => {
function waitForActivation(serviceWorker) {
serviceWorker.addEventListener('statechange', () => {
if (serviceWorker.state == 'activated') {
console.log('Installed new service worker.');
loadMainDartJs();
}
});
}
if (!reg.active && (reg.installing || reg.waiting)) {
// No active web worker and we have installed or are installing
// one for the first time. Simply wait for it to activate.
waitForActivation(reg.installing ?? reg.waiting);
} else if (!reg.active.scriptURL.endsWith(serviceWorkerVersion)) {
// When the app updates the serviceWorkerVersion changes, so we
// need to ask the service worker to update.
console.log('New service worker available.');
reg.update();
waitForActivation(reg.installing);
} else {
// Existing service worker is still good.
console.log('Loading app from service worker.');
loadMainDartJs();
}
});
// If service worker doesn't succeed in a reasonable amount of time,
// fallback to plaint <script> tag.
setTimeout(() => {
if (!scriptLoaded) {
console.warn(
'Failed to load app from service worker. Falling back to plain <script> tag.',
);
loadMainDartJs();
}
}, 4000);
});
} else {
// Service workers not supported. Just drop the <script> tag.
loadMainDartJs();
}
</script>
<!-- Initialize Firebase -->
<script src="/__/firebase/9.0.2/firebase-app.js"></script>
<script src="/__/firebase/9.0.2/firebase-analytics.js"></script>
<script src="/__/firebase/init.js"></script>
<!-- Initialize app -->
<script src="main.dart.js?version=15 " type="application/javascript"></script>
</body>
</html>

Found an answer to the issue I was facing. Here is the link to the same:
Bootstrap Responsive Design Fails with Web Forwarding
This is because you are using a framed redirect which essentially loads up the target website in an iFrame. Doing so loses any responsive capabilities. What you are best doing is changing your web forwarding method to actually forward to the new URL using a non-framed redirect. This will then properly load up the target URL in the users browser and all the responsive capabilities that go with it.

Related

Flutter Web: SPA: using URL parameters in meta data tags

I would like to get the parameters in a URL and use them to generate an og:image meta tag in my SPA. The specific purpose is to have a dynamic thumbnail for a given url. The idea is for crawlers to be able to find the appropriate thumbnail.
example URL:
https://my.app/#/post?uid=abc&pid=123
These two parameters will not necessarily always be included. I hope it won't cause an issue.
My understanding is that crawlers generally only check the html for metadata. How could I include a bit of code in my html before the metadata? (I am relatively new to HTML)
Would I be able to put a script in the head tag? Are variable in the script available outside of the script? Can I use variable in the URL address of my og:image tag?
<!DOCTYPE html>
<html>
<head>
<meta property="og:image" content="https://my.app/{uid}/{pid}/thumb.png" />
<meta charset="UTF-8">
<meta content="IE=Edge" http-equiv="X-UA-Compatible">
<meta name="description" content="Get Dressed. Better than you ever had">
<!-- iOS meta tags & icons -->
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black">
<meta name="apple-mobile-web-app-title" content="vestiqweb">
<link rel="apple-touch-icon" href="icons/Icon-192.png">
<!-- Favicon -->
<link rel="shortcut icon" type="image/png" href="favicon.png"/>
<title>VESTIQ</title>
<link rel="manifest" href="manifest.json">
</head>
<body id="app-container">
<script>
if ('serviceWorker' in navigator) {
window.addEventListener('load', function () {
navigator.serviceWorker.register('flutter_service_worker.js');
});
}
</script>
<script src="https://www.gstatic.com/firebasejs/7.17.1/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/7.14.4/firebase-firestore.js"></script>
<script src="https://www.gstatic.com/firebasejs/7.17.1/firebase-auth.js"></script>
<script src="https://www.gstatic.com/firebasejs/7.17.1/firebase-analytics.js"></script>
<script>
var firebaseConfig = {
//config info
};
firebase.initializeApp(firebaseConfig);
firebase.analytics();
</script>
<script src="main.dart.js?version=14" type="application/javascript"></script>
</body>
</html>
I was able to put a script before the meta tags and used window.location.href to get the URL. I used URLSearchParams to extract the parameters. However, I can only get the second parameter and not the first. If I add an '&' before the uid it works, but makes the url look weird... "?&uid"
<script>
const queryString = window.location.href;
const urlParams = new URLSearchParams(queryString);
const uid = urlParams.get('uid')
const pid = urlParams.get('pid')
if (uid != null && pid != null)
document.getElementById('urlThumb').content = `https://my.app/posts%2F${uid}%2F${pid}%2Furl_thumb.jpg?alt=media`;
</script>

ASP.NET Core - serve different HTML file for SPA?

Question
How can I serve different HTML (entry) files for an SPA application (Vue) in ASP.NET Core?
Explanation
Depending on a condition, I would like to serve a different HTML page (much like a controller would do for a non-SPA). The page would still include the entry point for Vue apps <div id="app">, but some other changes should be done before serving the HTML.
I know I somehow have to change the startup.cs file because that renders the HTML with app.UseStaticFiles() and app.UseSPAStaticFiles()
Example
Condition 1 is fulfilled, base.html is served from client -> public -> base.html
Condition 2 is fulfilled instead, special.html is served from client -> public -> special.html
Code
The basic HTML looks something like this:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<link rel="icon" href="<%= BASE_URL %>favicon.ico">
<title>Title</title>
</head>
<body>
<noscript>
<strong>We're sorry but this webpage doesn't work properly without JavaScript enabled. Please enable it to
continue.</strong>
</noscript>
<div id="app"></div>
<!-- built files will be auto injected -->
</body>
</html>
The important parts of startup.cs looks like this:
services.AddSpaStaticFiles(configuration =>
{
configuration.RootPath = "ClientApp/dist";
});
// ....
app.UseStaticFiles();
app.UseSpaStaticFiles();
// ....
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller}/{action=Index}/{id?}");
if (env.IsDevelopment())
{
endpoints.MapToVueCliProxy(
"{*path}",
new SpaOptions { SourcePath = "ClientApp" },
npmScript: "serve",
regex: "Compiled successfully");
}
// Add MapRazorPages if the app uses Razor Pages. Since Endpoint Routing includes support for many frameworks, adding Razor Pages is now opt -in.
endpoints.MapRazorPages();
});
// ....
app.UseSpa(spa =>
{
spa.Options.SourcePath = "ClientApp";
});

Next.js PWA (Service Worker + Manifest.json)

I am using Next.js to develop a Server Side Rendering website and I want to make it a Progressive Web App but the problem I couldn't find the way to make it happen correctly.
When I build the application it serves correctly the service worker but there is no manifest.json and in some projects examples it serves the manifest.json but I tried it in Lighthouse audit and it says
Service worker does not successfully serve the manifest's start_url
One of the examples I used
Create Next App With Service Worker Precache
I think that the problem is that the start_url is . or / and not a valid file because in Next.js there is no index.html to serve from the start.
In summary
I am looking for an example using Next.js to build it to a dist folder and when I serve it it has a valid Service Worker and a valid Web Manifest.
A. Some file are expected to be found at "/"
You have this error because browsers expect some files to be served from the root of the server, including:
/manifest.json
/sitemap.xml
/favicon.ico
/robots.txt
/browserconfig.xml
/site.webmanifest
While the majority of these paths can be set with meta tags, older browsers just ignore them and error if these exact file names are not served.
B. Configure alternative paths and use NextJS static file
At the time of writing, there is ongoing work for supporting offline in NextJS. But it's not ready yet.
If you don't need to support older browsers and you don't want advanced SEO, you can use NextJS's Head component (see documentation) to define the manifest.json path like you would for any NextJS static file:
import Head from "next/head"
export default () => (
<Head>
<link rel="manifest" href="/static/manifest.json" />
<link rel="manifest" href="/static/site.webmanifest" />
<link rel="shortcut icon" href="/static/favicon.ico"
</Head>
)
Please note that robots.txt cannot be serve from a subdirectory (source), so this solution is not a good fit if you need to define this file.
C. Serve these files like expected
The proper solution would be to serve these files from your express server like so
const { createServer } = require('http')
const { parse } = require('url')
const next = require('next')
const { join } = require('path')
const port = parseInt(process.env.PORT, 10) || 3000
const dev = process.env.NODE_ENV !== 'production'
const app = next({ dev })
const handle = app.getRequestHandler()
app.prepare()
.then(() => {
createServer((req, res) => {
const parsedUrl = parse(req.url, true)
const rootStaticFiles = [
'/manifest.json',
'/sitemap.xml',
'/favicon.ico',
'/robots.txt',
'/browserconfig.xml',
'/site.webmanifest',
]
if (rootStaticFiles.indexOf(parsedUrl.pathname) > -1) {
const path = join(__dirname, 'static', parsedUrl.pathname)
app.serveStatic(req, res, path)
} else {
handle(req, res, parsedUrl)
}
})
.listen(port, (err) => {
if (err) throw err
console.log(`> Ready on http://localhost:${port}`)
})
})
Note: This code directly comes from the NextJS examples repository
here are the steps to make your next.js progressive. check the example
npm i next-pwa
next.config.json
const withPWA = require("next-pwa");
module.exports = withPWA({
pwa: {
dest: "public",
},
...
});
add manifest.json and icons to public folder from the example. However, icons directory is missing "maskable_icon.png". So create a maskable icon from here then add this to "manifest.json".
{
"src": "path/to/maskable_icon.png",
"sizes": "196x196",
"type": "image/png",
"purpose": "any maskable"
}
add those tags to import Head from "next/head". Head is used for better SEO setting. check the documentation*
<meta charSet="utf-8" />
<meta httpEquiv="X-UA-Compatible" content="IE=edge" />
<meta
name="viewport"
content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no"
/>
<meta name="description" content="Description" />
<meta name="keywords" content="Keywords" />
<title>Next.js PWA Example</title>
<link rel="manifest" href="/manifest.json" />
<link
href="/icons/favicon-16x16.png"
rel="icon"
type="image/png"
sizes="16x16"
/>
<link
href="/icons/favicon-32x32.png"
rel="icon"
type="image/png"
sizes="32x32"
/>
<link rel="apple-touch-icon" href="/apple-icon.png"></link>
<meta name="theme-color" content="#317EFB" />
</Head>
lastly check if it is working. add Lighhouse extension to chrome dev tools from chrome app store and run start the performance.

AdMob banner not displayed in Phonegap

i want to create an android app using phonegap , with a simple basic HTML page as showed in this tutorial.
http://pointdeveloper.com/how-to-add-banner-ads-to-phonegap...
https://phonegap.com/blog/2016/08/09/appfeel-guest-post/
After adding the following line to "config.xml"
<gap:plugin name="phonegap-admob" source="npm"/>
here is my "index.html" file
<!DOCTYPE html>
<html>
<head>
<title>Title Of The App</title>
<meta name="viewport" content="user-scalable=no, initial-scale=1,
maximum-scale=1, minimum-scale=1, width=device-width, min-height=device-
height" />
<link rel="stylesheet" type="text/css" href="css/index.css">
</head>
<body onload="domLoaded()">
<header>pointDeveloper.com</header>
<div class="wrapper">Please Subscribe To My Channel and like the video
</div>
<footer class="footer">This is spartaaaa</footer>
<script src="cordova.js"></script>
<script type="text/javascript" src="js/index.js" ></script>
<script type="text/javascript" >
function adSetter(){
alert(navigator.userAgent);
var admobid = {};
// select the right Ad Id according to platform
if( /(android)/i.test(navigator.userAgent) ) {
admobid = { // for Android
banner: 'ca-app-pub-6136762217480399/8690615372',
interstitial: 'ca-app-pub-6136762217480399/5002296586'
};
} else if(/(ipod|iphone|ipad)/i.test(navigator.userAgent)) {
admobid = { // for iOS
banner: 'ca-app-pub-6869992474017983/4806197152',
interstitial: 'ca-app-pub-6869992474017983/7563979554'
};
} else {
admobid = { // for Windows Phone
banner: 'ca-app-pub-6869992474017983/8878394753',
interstitial: 'ca-app-pub-6869992474017983/1355127956'
};
}
if(AdMob) AdMob.createBanner( {
isTesting:true, //Remove this Before publishing your app
adId:admobid.banner,
position:AdMob.AD_POSITION.BOTTOM_CENTER,
autoShow:true} );
}
function onDeviceReady(){
alert("device ready");
adSetter();
}
function domLoaded(){
document.addEventListener("deviceready", onDeviceReady, false);
}
</script>
</body>
</html>
After lot of testing on my android phone, even exporting the apk in the phonegap build,
the apps is displpayed , but the bottom banner is nowhere
did i miss something ?
thanks in advance
edit: Here are the errors shown in Chrome JavaScript Debugger Tools
Uncaught ReferenceError: domLoaded is not defined
at onload ((index):10)
:3000/cordova_plugins.js Failed to load resource: the server responded with a status of 500 (Internal Server Error)
(index):27 Uncaught ReferenceError: admob is not defined
at initAds ((index):27)
at Channel.onDeviceReady ((index):97)
at Channel.fire (cordova.js:777)
at cordova.js:231
:3000/favicon.ico Failed to load resource: the server responded with a status of 404 (Not Found)
Its likely that you need to configure the cordova-plugin-whitelist to allow Admob to access the network.
edit:
Add the plugin to your config.xml:
<plugin name="cordova-plugin-whitelist" />
Start with fully open access (in your config.xml) and see if your request is successful:
<access origin="*" />
If that works then you should determine which exact domains you need access to and restrict to that. If your requests still don't work then the problem may be somewhere else. Connect a JavaScript debugger (safari or Chrome) and see what errors are being thrown.

jquery-mobile style does not work with phonegap code

I have a phonegap application that is styled with jquery mobile. The phonegap part works. But the buttons are not styled in jquery style but normal HTML style. What is the conflict here? I cannot seem to find it.
<!DOCTYPE html>
<!--
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
-->
<html>
<head>
<meta charset="utf-8" />
<meta name="format-detection" content="telephone=no" />
<!-- WARNING: for iOS 7, remove the width=device-width and height=device-height attributes. See https://issues.apache.org/jira/browse/CB-4323 -->
<meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width, height=device-height, target-densitydpi=device-dpi" />
<link rel="stylesheet" type="text/css" href="css/index.css" />
<title>Hello World</title>
<link href="jquery-mobile/jquery.mobile.structure-1.0.min.css" rel="stylesheet" type="text/css"/>
<link href="css/style.css" rel="stylesheet" type="text/css"/>
<script src="jquery-mobile/jquery-1.6.4.min.js" type="text/javascript"></script>
<script src="jquery-mobile/jquery.mobile-1.0.min.js" type="text/javascript"></script>
<script type="text/javascript" src="phonegap.js"></script>
<script type="text/javascript" charset="utf-8">
var pictureSource; // picture source
var destinationType; // sets the format of returned value
// Wait for device API libraries to load
//
document.addEventListener("deviceready",onDeviceReady,false);
// device APIs are available
//
function onDeviceReady() {
pictureSource=navigator.camera.PictureSourceType;
destinationType=navigator.camera.DestinationType;
}
// Called when a photo is successfully retrieved
//
function onPhotoDataSuccess(imageData) {
// Uncomment to view the base64-encoded image data
// console.log(imageData);
// Get image handle
//
var smallImage = document.getElementById('smallImage');
// Unhide image elements
//
smallImage.style.display = 'block';
// Show the captured photo
// The in-line CSS rules are used to resize the image
//
smallImage.src = "data:image/jpeg;base64," + imageData;
}
// Called when a photo is successfully retrieved
//
function onPhotoURISuccess(imageURI) {
// Uncomment to view the image file URI
// console.log(imageURI);
// Get image handle
//
var largeImage = document.getElementById('largeImage');
// Unhide image elements
//
largeImage.style.display = 'block';
// Show the captured photo
// The in-line CSS rules are used to resize the image
//
largeImage.src = imageURI;
}
// A button will call this function
//
function capturePhoto() {
// Take picture using device camera and retrieve image as base64-encoded string
navigator.camera.getPicture(onPhotoDataSuccess, onFail, { quality: 50,
destinationType: destinationType.DATA_URL });
}
// A button will call this function
//
function capturePhotoEdit() {
// Take picture using device camera, allow edit, and retrieve image as base64-encoded string
navigator.camera.getPicture(onPhotoDataSuccess, onFail, { quality: 20, allowEdit: true,
destinationType: destinationType.DATA_URL });
}
// A button will call this function
//
function getPhoto(source) {
// Retrieve image file location from specified source
navigator.camera.getPicture(onPhotoURISuccess, onFail, { quality: 50,
destinationType: destinationType.FILE_URI,
sourceType: source });
}
// Called if something bad happens.
//
function onFail(message) {
alert('Failed because: ' + message);
}
</script>
</head>
<body>
<button onclick="capturePhoto();">Capture Photo</button> <br>
<button onclick="capturePhotoEdit();">Capture Editable Photo</button> <br>
<button onclick="getPhoto(pictureSource.PHOTOLIBRARY);">From Photo Library</button><br>
<button onclick="getPhoto(pictureSource.SAVEDPHOTOALBUM);">From Photo Album</button><br>
<img style="display:none;width:60px;height:60px;" id="smallImage" src="" />
<img style="display:none;" id="largeImage" src="" />
</body>
</html>
I would first recommend upgrading jQuery and jQuery Mobile to recent versions. You should try jQuery 1.10.1 (I don't think jQM supports 1.11 yet) and jQuery Mobile 1.4.0 and see if that straightens you out.
Just use the script like this first its needs jquery, second jquerymobile and finally it needs jquery mobile css like this you can try it will definitely work.
<script type="text/javascript" src="js/jquery-2.1.1.min.js"></script>
<script type="text/javascript" src="js/jquery.mobile-1.4.4.min.js"></script>
<link rel="stylesheet" href="js/jquery.mobile-1.4.4.min.css" />
Try it.