flutter web set splash by url - splash-screen

Now I have a splash in my index.html:
<body>
<script>
if ('serviceWorker' in navigator) {
window.addEventListener('flutter-first-frame', function () {
navigator.serviceWorker.register('flutter_service_worker.js');
});
}
</script>
<img src="img/splash2.png" class="center"/>
How can I change the body according to the current url? I want to show different splash images for different pages.

Related

How to check if it <script> tag exists with RTL

I am writing a test to check if it loads script correctly. This script is to load scripts for user tracking.
Here is my pseudo code.
import Head from 'next/head';
export const TrackingScript = () => {
return (
<Head>
<script
type="text/javascript"
src="https://..."
</script>
</Head>
)
}
I want to write a test
import { render } from '#testing-library/react';
import { TrackingScript } from './TrackingScript';
it('loads tracking script correctly', () => {
render(TrackingScript);
...
})

Flutter web app not getting any http response

I have finished my Flutter app and it is running fine on both mobile platforms, iOS and Android.
Now I am trying to run the web app on my local Chrome navigator. The app is running but the screens where a http request is needed is not working.
The app uses Firebase and Cloud Messaging. I have solved all Firebase related errors when executing the web app, but the http parts of the app are not getting any response from the web server.
Here you have the index.html file from my project:
<!DOCTYPE html>
<html>
<head>
<base href="$FLUTTER_BASE_HREF">
<meta charset="UTF-8">
<meta content="IE=Edge" http-equiv="X-UA-Compatible">
<meta name="description" content="A new Flutter project.">
<!-- 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="proyecto_flutter">
<link rel="apple-touch-icon" href="icons/Icon-192.png">
<title>proyecto_flutter</title>
<link rel="manifest" href="manifest.json">
<link rel="stylesheet" type="text/css" href="splash/style.css">
</head>
<body style="position: fixed; inset: 0px; overflow: hidden; padding: 0px; margin: 0px; user-select: none; touch-action: none; font: 14px sans-serif; color: red;">
<script type="module">
// Import the functions you need from the SDKs you need
import { initializeApp } from "https://www.gstatic.com/firebasejs/9.6.9/firebase-app.js";
import { getAnalytics } from "https://www.gstatic.com/firebasejs/9.6.9/firebase-analytics.js";
// TODO: Add SDKs for Firebase products that you want to use
// https://firebase.google.com/docs/web/setup#available-libraries
// Your web app's Firebase configuration
// For Firebase JS SDK v7.20.0 and later, measurementId is optional
const firebaseConfig = {
apiKey: "AIzaSyAErdmk...",
authDomain: "...",
projectId: "...",
storageBucket: "...",
messagingSenderId: "...",
appId: "...",
measurementId: "..."
};
// Initialize Firebase
const app = initializeApp(firebaseConfig);
<script src="https://www.gstatic.com/firebasejs/8.4.1/firebase-messaging.js"></script>
</script>
<script>
if ("serviceWorker" in navigator) {
window.addEventListener("load", function () {
// navigator.serviceWorker.register("/flutter_service_worker.js");
navigator.serviceWorker.register("/firebase-messaging-sw.js");
});
}
</script>
<script>
var serviceWorkerVersion = null;
var scriptLoaded = false;
function loadMainDartJs() {
if (scriptLoaded) {
return;
}
scriptLoaded = true;
var scriptTag = document.createElement('script');
scriptTag.src = 'main.dart.js';
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>
<picture id="splash">
<source srcset="splash/img/light-1x.png 1x, splash/img/light-2x.png 2x, splash/img/light-3x.png 3x, splash/img/light-4x.png 4x" media="(prefers-color-scheme: light) or (prefers-color-scheme: no-preference)">
<source srcset="splash/img/dark-1x.png 1x, splash/img/dark-2x.png 2x, splash/img/dark-3x.png 3x, splash/img/dark-4x.png 4x" media="(prefers-color-scheme: dark)">
<img class="center" aria-hidden="true" src="splash/img/light-1x.png" />
</picture>
</body>
</html>
I would like to make the web app working just like the mobile apps.
What am I missing?
EDIT
Screenshot from iOS app:
Screenshot for web

Directly Hitting static css file url( http://localhost:3000/css/style.css ) response is working but not applied on ejs template elements?

Hye guys I am newbie in node.js .
I am working with ejs partial template . I have been stuck for days in this issue where i have public/css/style.css file in root directory .
where i am accessing this file from views/contact.ejs and views/home.ejs
Contact.ejs
!-- begin snippet: js hide: false console: true babel: false -->
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="/public/css/style.css" type=β€œtext/cssβ€œ>
</head>
<body>
<%- include('partialComponents/naviagations.ejs') %>
<H3>CONTACTS US !</H3>
<h2>LEARN THE BEST CODE TECHNIQUES HERE ....</h2>
<h2>EJS FILE TEMPLATE </h2>
</body>
</html>
main.js
var express = require('express');
var app = express();
app.set('view engine', 'ejs');
//app.set('views', '/views'); // settings the path to view folder to express can locate
//by default express will check the view folder in first root to the js file
app.use(express.static('public'))
app.get('/profile/:id', (req, res) => {
var data = {
age: 23,
job: 'software developer',
hobbies: ['eating', 'fishing', 'gaming']
}
console.log('hey');
res.render('profile', { name: req.params.id, data: data });
});
app.get('/home', (req, res) => {
res.render('home');
});
app.get('/', (req, res) => {
res.render('home');
});
app.get('/contact', (req, res) => {
res.render('contact');
});
app.listen(3000);
// console.log(__dirname + "");
style.css
body {
background-color: skyblue;
text-align: center;
}
h3 {
font-size: 50px;
font-family: Impact, Haettenschweiler, 'Arial Narrow Bold', sans-serif;
color: white;
}
h2 {
color: white;
}
.testid {
color: red;
}
here is my file structure
πŸ‘¨β€πŸ« You're missing in the <link href=""> because you have set public as your static folder, your style is in the location:http://localhost:3000/css/style.css. That is why when you call /public/css/style.css it cannot be found, because it will look for thepublic folder inside the public folder and you do not have it other than thecss folder there..
So, You can change your <link href=""/> with this code below πŸ‘‡:
<link rel="stylesheet" href="/css/style.css" href="text/css">
For an example: You can see on my codesandbox
Sandbox code: https://codesandbox.io/s/quirky-borg-ghwc0
For view only: https://ghwc0.sse.codesandbox.io/contact
I hope it can help you πŸ™.

setup properly Google Tag Manager on Nextjs with dataLayer?

What I have
My _document file:
import NextDocument, { Head } from 'next/document';
const GTM_TRACKING_ID = 'GTM-ID';
class WebAppDocument extends NextDocument {
render() {
return (
<html lang="es">
<Head>
{ /* Global Tag Manager (gtm.js) */}
{ /* => load GTM scripts according to environment variable */ }
<script dangerouslySetInnerHTML={{ __html: `window.dataLayer = window.dataLayer || []` }} />
<script
dangerouslySetInnerHTML={{
__html: `(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
})(window,document,'script','dataLayer','${GTM_TRACKING_ID}');
`,
}}
/>
</Head>
</html>
);
}
}
My _app file:
import NextApp from 'next/app';
const pushEvent = ({ event, pagePath, pageTitle }) => {
window.dataLayer.push({
event,
pagePath,
pageTitle,
});
};
class WebApp extends NextApp {
componentDidMount() {
// push data to Google Tag Manager
pushEvent({
event: 'PageView',
pagePath: window.location.pathname + window.location.search + window.location.hash,
pageTitle: document.title,
});
}
}
What I want
I've seen the example and used Router.events.on('routeChangeComplete', url => dataLayer.push({})) to execute dataLayer. Is this the best approach? Or is it better to run the code to populate the dataLayer in componentDidMount.
I want to load GTM scripts according to environment variable. How could this be achieved?

While Ejs file doesn't see css style?

Have problem in my express app. Have some ejs templates, where css style file applied correctly. For example "localhost***/page", but when i go to "localhost***/page/secondpage" my ejs doesn't see style even if i apply it.
A little bit of code
app.js
app.use(express.static(path.join(__dirname, 'public')));
//some code
app.use('/', require('./routes/index'));
app.use('/events', require('./routes/events'));
some routes
const express = require('express');
const router = express.Router();
router.get('/', function (req, res, next) {
let query = *db query*;
res.locals.connection.query(query, function (error, results, fields) {
if (error) throw error;
res.render('index', { title: 'Events', data: results });
});
});
router.get('/:id', function (req, res) {
let query = *db query*;
res.locals.connection.query(query, function (error, results, fields) {
if (error) throw error;
res.render('singleevent', { title: 'Event', data: results });
});
});
Head of localhost***/events page and of next page localhost***/events/singleevent
<head>
<meta charset="UTF-8">
<title>
<%= title %>|Minsk Events</title>
<link rel="stylesheet" href="css/style.css">
</head>
There are my dirs
You asked for css file related to the html file.
So if html file is placed under events, then css file should be at:
/events/css/style.css
etc.

Resources