Flutter Web : javascript Uncaught ReferenceError: Firebase is not defined? - firebase

I am trying to add firebase to my flutter web app, i keep getting this error and i dont know why anymore, i have tried everything
Google chrome console error
3(index):1 Unchecked runtime.lastError: The message port closed before a response was received.
zone.dart:1175 Uncaught ReferenceError: firebase is not defined
at Object.X1 (core.dart:54)
at cloud_firestore_web.dart:36
at Qi.a (async_patch.dart:315)
at Qi.$2 (async_patch.dart:340)
at Object.an (async_patch.dart:245)
at Object.BB (main.dart:8)
at js_helper.dart:2677
at js_helper.dart:2677
at dartProgram (js_helper.dart:2677)
at js_helper.dart:2677
here is my index.html file
<!DOCTYPE html>
<html>
<head>
<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="weepay_web">
<link rel="apple-touch-icon" href="icons/Icon-192.png">
<!-- Favicon -->
<link rel="icon" type="image/png" href="favicon.png"/>
<title>weepay_web</title>
<link rel="manifest" href="manifest.json">
<script src='https://cdn.firebase.com/js/client/2.2.1/firebase.js'></script>
<script src='https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js'></script>
</head>
<body>
<!-- The core Firebase JS SDK is always required and must be listed first -->
<script src="https://www.gstatic.com/firebasejs/7.15.1/firebase-app.js"></script>
<!-- TODO: Add SDKs for Firebase products that you want to use
https://firebase.google.com/docs/web/setup#available-libraries -->
<script src="https://www.gstatic.com/firebasejs/7.15.1/firebase-firestore.js"></script>
<script>
// Your web app's Firebase configuration
// For Firebase JS SDK v7.20.0 and later, measurementId is optional
var firebaseConfig = {
apiKey: "AIzaSyBqi_VL9n1FGXfK2LifaQjVGIm4XN3Sdkw",
authDomain: "wepay-c6dad.firebaseapp.com",
databaseURL: "https://wepay-c6dad.firebaseio.com",
projectId: "wepay-c6dad",
storageBucket: "wepay-c6dad.appspot.com",
messagingSenderId: "10570764732",
appId: "1:10570764732:web:0f56355e304272af91dbb9",
measurementId: "G-539E2WLH93"
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
</script>
<!-- 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>
if ('serviceWorker' in navigator) {
window.addEventListener('load', function () {
navigator.serviceWorker.register('flutter_service_worker.js?v=3346340368');
});
}
</script>
<script src="main.dart.js?v=3346340368" type="application/javascript"></script>
</body>
</html>
here is my pubspec yaml file
name: weepay_web
description: A new Flutter project.
# The following line prevents the package from being accidentally published to
# pub.dev using `pub publish`. This is preferred for private packages.
publish_to: 'none' # Remove this line if you wish to publish to pub.dev
# The following defines the version and build number for your application.
# A version number is three numbers separated by dots, like 1.2.43
# followed by an optional build number separated by a +.
# Both the version and the builder number may be overridden in flutter
# build by specifying --build-name and --build-number, respectively.
# In Android, build-name is used as versionName while build-number used as versionCode.
# Read more about Android versioning at https://developer.android.com/studio/publish/versioning
# In iOS, build-name is used as CFBundleShortVersionString while build-number used as CFBundleVersion.
# Read more about iOS versioning at
# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
version: 1.0.0+1
environment:
sdk: ">=2.7.0 <3.0.0"
dependencies:
flutter:
sdk: flutter
# The following adds the Cupertino Icons font to your application.
# Use with the CupertinoIcons class for iOS style icons.
cupertino_icons: ^1.0.0
dev_dependencies:
flutter_test:
sdk: flutter
firebase_core_web: ^0.2.1
cloud_firestore: ^0.14.3
# For information on the generic Dart part of this file, see the
# following page: https://dart.dev/tools/pub/pubspec
# The following section is specific to Flutter.
flutter:
# The following line ensures that the Material Icons font is
# included with your application, so that you can use the icons in
# the material Icons class.
uses-material-design: true
# To add assets to your application, add an assets section, like this:
# assets:
# - images/a_dot_burr.jpeg
# - images/a_dot_ham.jpeg
# An image asset can refer to one or more resolution-specific "variants", see
# https://flutter.dev/assets-and-images/#resolution-aware.
# For details regarding adding assets from package dependencies, see
# https://flutter.dev/assets-and-images/#from-packages
# To add custom fonts to your application, add a fonts section here,
# in this "flutter" section. Each entry in this list should have a
# "family" key with the font family name, and a "fonts" key with a
# list giving the asset and other descriptors for the font. For
# example:
# fonts:
# - family: Schyler
# fonts:
# - asset: fonts/Schyler-Regular.ttf
# - asset: fonts/Schyler-Italic.ttf
# style: italic
# - family: Trajan Pro
# fonts:
# - asset: fonts/TrajanPro.ttf
# - asset: fonts/TrajanPro_Bold.ttf
# weight: 700
#
# For details regarding fonts from package dependencies,
# see https://flutter.dev/custom-fonts/#from-packages
and here is my main.dart file
import 'package:flutter/material.dart';
import './pay_link.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
initialRoute: "/home",
routes: {
"/home": (context) => Container(color:Colors.orange)
},onGenerateRoute: (settings) {
List<String> pathComponents = settings.name.split('/');
if (pathComponents[1] == 'link') {
return MaterialPageRoute(
builder: (context) {
return PayLinkScreen(payment_link:pathComponents.last);
},
);
} else
return MaterialPageRoute(
builder: (context) {
return Container(color:Colors.orange);
},
);
},
title: 'Flutter Demo',
theme: ThemeData(
// This is the theme of your application.
//
// Try running your application with "flutter run". You'll see the
// application has a blue toolbar. Then, without quitting the app, try
// changing the primarySwatch below to Colors.green and then invoke
// "hot reload" (press "r" in the console where you ran "flutter run",
// or simply save your changes to "hot reload" in a Flutter IDE).
// Notice that the counter didn't reset back to zero; the application
// is not restarted.
primarySwatch: Colors.blue,
// This makes the visual density adapt to the platform that you run
// the app on. For desktop platforms, the controls will be smaller and
// closer together (more dense) than on mobile platforms.
visualDensity: VisualDensity.adaptivePlatformDensity,
),
);
}
}
...................................................................................................................................................................................

I would love to help you but could you share the error you get in the Chrome console log?
Usually, the problem is that you are using firestore and others but did not include them in the index.html.
For example:
<!-- TODO: Add SDKs for Firebase products that you want to use
https://firebase.google.com/docs/web/setup#available-libraries -->
<script src="https://www.gstatic.com/firebasejs/8.0.1/firebase-analytics.js"></script>
<script src="https://www.gstatic.com/firebasejs/8.0.1/firebase-firestore.js"></script>
If you share more information on your error I could try to help you better but this is my first assumption.
More info you can find on https://firebase.google.com/docs/web/setup#available-libraries
After your additional info, I looked closer at your code and it seems that you do not add the scripts in the proper order.
Please look at my standard Flutter Web App index.html:
<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>
if ('serviceWorker' in navigator) {
window.addEventListener('flutter-first-frame', function () {
navigator.serviceWorker.register('flutter_service_worker.js');
});
}
</script>
<!-- The core Firebase JS SDK is always required and must be listed first -->
<script src="https://www.gstatic.com/firebasejs/8.0.1/firebase-app.js"></script>
<!-- TODO: Add SDKs for Firebase products that you want to use
https://firebase.google.com/docs/web/setup#available-libraries -->
<script src="https://www.gstatic.com/firebasejs/8.0.1/firebase-analytics.js"></script>
<script src="https://www.gstatic.com/firebasejs/8.0.1/firebase-firestore.js"></script>
<script>
// Your web app's Firebase configuration
// For Firebase JS SDK v7.20.0 and later, measurementId is optional
var firebaseConfig = {
apiKey: "XXXXXXXXXXXXXXX",
authDomain: "xxxxxxx.firebaseapp.com",
databaseURL: "https://xxxxxxx.firebaseio.com",
projectId: "xxxx-id",
storageBucket: "xxxxxxx.appspot.com",
messagingSenderId: "XXXXXXXXXX",
appId: "1:XXXXXXXX:web:XXXXXXXXXX",
measurementId: "G-XXXXXXXXXXX"
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
firebase.analytics();
</script>
<script src="main.dart.js" type="application/javascript"></script>
</body>
So all the scripts are in the body not the head.

Related

Svelte app returning "unexpected character # " error when running project

I added a semantic-ui-css-only npm module in a svelte app project. Imported the module import "../node_modules/semantic-ui-css/semantic.css"; in main.js file. When I run npm run dev I get this error Error: Unexpected character '#' (Note that you need plugins to import files that are not JavaScript) Not sure what the solution is. My hypothesis is the # characters in the CSS causing issues no.
Semantic development is dead but you can replace it with Fomantic
read this issue Is Semantic UI development dead ?
and this The future of Fomantic as v3.0
After talking about this, how about this rollup plugin ?
https://www.npmjs.com/package/rollup-plugin-css-only
main.js
import App from './App.svelte';
import 'fomantic-ui-css/semantic.min.css';
const app = new App({
target: document.body,
props: {
name: 'world'
}
});
export default app;
rollup.config.js
...
import css from 'rollup-plugin-css-only';
...
plugins: [
svelte({
dev: !production,
css: css => {
css.write('public/build/bundle.css');
}
}),
css({ output: './public/build/base.css' }),
...
...
]
index.html
<link rel='stylesheet' href='/build/base.css'>
<link rel='stylesheet' href='/build/bundle.css'>

Fonts not found: React-slick + nextjs

I am trying to use react-slick inside a NextJs project. The carousel works fine but I have some problems importing the fonts used in the css files.
I have tried the following:
npm install slick-carousel
and imported the css in the component where the react-slick module is used:
import "slick-carousel/slick/slick.css";
import "slick-carousel/slick/slick-theme.css";
When i run the application I get the following error in the network log:
404 Not found on both slick.woff and slick.ttf
I found some other responses where they have added the following to the next.config.js:
const withSass = require('#zeit/next-sass')
const withFonts = require('next-fonts');
const withCss = require('#zeit/next-css')
module.exports = withFonts(withSass(withCss({
env: {
environment: 'development'
},
enableSvg: true,
webpack: function (config) {
config.module.rules.push({
test: /\.(eot|woff|woff2|ttf|svg|png|jpg|gif)$/,
use: {
loader: 'url-loader',
options: {
limit: 100000,
name: '[name].[ext]'
}
}
})
return config
},
cssLoaderOptions: {
url: false
},
})))
I've tried both with and without the withFonts module.
If i add the direct urls in the <Head>it will work:
<Head>
<>
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.6.0/slick.min.css" />
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.6.0/slick-theme.min.css" />
</>
</Head>
But will rather get the fonts to work instead.
Anyone with some suggestion to get the fonts to load in Nextjs?
Not a solution, but I solved it another way.
As I am going to style most of the stuff that requires fonts, i decided to just copy the css from slick-carousel and delete all font references. Override arrow left, arrow right as well as the dots.
Not a solution on the problem stated above but fix my issue.
Pasting both files in public directory with next font installed should resolve 404 error

Firebase Auth + Electron = failure?

I'm trying to get firebase auth working with electron. I already have it working with iOS and Android and would like to use the same for the desktop version of the app.
What I'm mainly trying with is the google sign in. Using firebase's web version ends up with a failure where localhost isn't accepted for signing in. I have tried the node.js version of the code but I can't get that working either.
Google this: https://www.google.com/search?q=firebase+auth+electron
And you'll see all I have tried and all stackoverflow questions I have looked through. Some people say they have it working but I have found no working examples. Is this a lost cause or could someone point me in the right direction?
A lot of people seems to have the same issue but no answers.
you will have to set nativeWindowOpen to true inside webPreferences in your main windows. Like so:
mainWindow = new BrowserWindow(
{
width: 1280,
height: 720,
webPreferences: {
nodeIntegration: false,
preload: path.join(__dirname, 'preload.js'),
nativeWindowOpen: true
}
}
);
One way to make this work is to run a local server which serves the page you want to display. Then in your electron window load that local server url.
Because the Firebase libraries will complain if loaded directly in an electron window, but you can get around it using a local server like this:
import {
app,
BrowserWindow
} from 'electron'
import ex from 'express'
import path from 'path'
const express = ex()
let win
const port = 12345
const appPath = app.getAppPath()
express.use(require('express').static(path.join(appPath, '/')))
express.get('/', (_, res) => res.sendFile(path.join(appPath, '/index.html')))
express.listen(port, () => console.log('Running on ' + port))
function getWindow () {
if (win === undefined) {
// Create the browser window.
win = new BrowserWindow({
frame: false,
transparent: true,
alwaysOnTop: true,
width: 1280,
height: 768,
center: true
})
win.loadURL('http://localhost:' + port)
}
return win
}
app.on('ready', () => {
getWindow().show()
})
The above code would be your index.js which you'd run when you run electron. Then in index.html which is served over the local webserver you load the firebase web libraries.
<!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>Example</title>
</head>
<body>
<script src="/__/firebase/6.3.0/firebase-app.js"></script>
<script src="/__/firebase/6.3.0/firebase-auth.js"></script>
</body>
</html>
what you could look into is something that achieves what you need but not exactly what you want. Whilst the google sign in module is iffy to say the least with electron, I've found success using the createUserWithEmailAndPassword function with Firebase auth, check that out
I was facing the same problem when connecting firebase and electron.js with React.js but there's a simple way that allows you to use firebase popup authentication. Inside the main process when creating a new browserWindow. Under webPreferences object add or set the property nativeWindowOpen to true. Make sure that your webPreferences object has the property nativeWindowOpen set to true.
Example
window = new electron.BrowserWindow({
width: 1200,
height: 650,
webPreferences:{
nodeIntegration: true,
enableRemoteModule: true,
nativeWindowOpen: true, // this allows you to use popups when doing authentication using firebase in an electron app
}
})
Good luck ✔✔✨✨

Webpack-React with server-side-rendering: linking to css file in server template with hash name

I'm preparing a starter for react from scratch, here is the code: https://github.com/antondc/react-starter
I managed to set up bundling for client and server, with css modules and less, and now I'm with server side rendering. I'm doing that with a js template:
// src/server/views/index.ejs
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>INDEX.EJS</title>
<link rel="stylesheet" type="text/css" href="assets/index.css">
</head>
<body>
<div id="app"></div>
<script src="/assets/bundle.js"></script>
</body>
</html>
As you see, the link to the css file is harcoded there. But in my Webpack configuration I have this file name hashed, because I want to prevent caching from browsers when I update the code on development.
I am wondering how can I link the css file there. Now in the template I have href="assets/index.css, but the css file is in /dist/assets/d47e.css.
It would be great if would be possible to do something like href="assets/*.css, but is not possible, so what is the common approach for a problem like this one?
Thanks!
It depends.
Step 1: Get the current asset name
To get the current name of the generated webpack css/js files, you can use the assets-webpack-plugin. This will (with default config) generate an assets.json file in your output folder with essentially this structure:
{
"bundle_name": {
"asset_kind": "/public/path/to/asset"
}
}
Step 2a: Your html is rendered from a template (pug/jade/what ever)
// in your render code
const assets = require('<webpack-output-folder>/assets.json');
// ...
res.render('template', {
scripts: [{src: `${WEBPACK_PUBLIC_PATH}/${assets.myEntryPointName.js}` }],
links: [{href: `${WEBPACK_PUBLIC_PATH}/${assets.myEntryPointName.css}` rel: 'stylesheet' }],
});
// in your template (example for pug)
// ...
each link in links
link(rel=link.rel href=link.href)
// ...
each script in scripts
script(src=script.src)
// ...
Step 2b: Your html is static
You need to update the html (using a script) with the information from the asset.json file. This script needs to be run after webpack. Something like
const assets = require('<webpack-output-folder>/assets.json');
const fs = require('fs');
const css = /assets\/[a-z0-9]*\.css/i;
const js = /assets\/[a-z0-9]*\.js/i;
fs.readFile('<yourhtml>.html', (err, data) => {
// ... (error handling)
const updatedCss = data.replace(css, assets.myEntryPointName.css);
const updatedJs = updatedCss.replace(js, assets.myEntryPointName.js);
fs.writeFile('<yourhtml>.html', updated, (err) => {
// ... (error handling)
});
});
You can use HTMLWebpackPlugin to generate an HTML file that will have your JS and CSS output inserted.

Enyo error: "Uncaught referenceError: App is not defined"

I am getting the error: "Uncaught referenceError: App is not defined" in my JS console when loading this Enyo app on my localhost. I am brand new to Enyo so I am still trying to learn the concepts of kinds and components.
app.js (in source folder):
enyo.kind({
name: "App",
kind: "FittableRows",
classes: "enyo-fit enyo-unselectable",
components: [
{
kind: "onyx.Toolbar",
layoutKind:"FittableColumnsLayout",
components: [
{
kind:onyx.Button,
style:"width:80px;background:green;",
ontap:"handleBtnBack",
content:"Back"
},
{
content:"Header",
style:"text-align:center;",
fit:true
},
{
kind:onyx.Button,
style:"width:80px;background:red;",
ontap:"handleBtnNext",
content:"Next"
}
]
},
{
kind: "Scroller",
horizontal:"hidden",
touch:true,
fit:true,
thumb:true,
components:[
{
tag:"h1",
//This is how we insert css class.
classes:"padding15px",
content:"This is content area...Hello World!!!"
}
]
},
{
kind: "onyx.Toolbar",
// The footer
layoutKind:"FittableColumnsLayout",
components:[
{
kind:"onyx.Button",
content:"Go Next Page",
ontap:"handleBtnNextPage",
fit:true
}
]
}
],
create: function(){
this.inherited(arguments);
console.log("App is created in memory");
},
rendered : function(){
this.inherited(arguments);
console.log("App is created in rendered into DOM");
},
handleBtnNextPage : function(inSender,inEvent){
new Page2().renderInto(document.body);
},
handleBtnNext: function(inSender,inEvent){
new Page2().renderInto(document.body);
},
handleBtnBack: function(inSender,inEvent){
//For each enyo event handler comes with inSender, the control that sends the event and the inEvent the actual event itself.
alert("Back Button");
}
});
package.js (in source folder):
enyo.depends(
// Layout library
"$lib/layout",
// Onyx UI library
"$lib/onyx", // To theme Onyx using Theme.less, change this line to $lib/onyx/source,
//"Theme.less", // uncomment this line, and follow the steps described in Theme.less
// CSS/LESS style files
"../assets/css/app.css",
// Include our default entry point
"App.js",
"Page2.js"
);
index.html (in root folder):
<!--My Copy-->
<!DOCTYPE html>
<html>
<head>
<title>IsGoodStuff.com Tutorial #2</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<link rel="shortcut icon" href="assets/favicon.ico"/>
<script src="enyo/enyo.js" type="text/javascript"></script>
<!-- -->
<script src="package.js" type="text/javascript"> </script>
</head>
<body>
<script type="text/javascript">
new App().renderInto(document.body);
</script>
</body>
</html>
If your index.html is in your root folder, but the main package.js is in the source folder, it's probably your script tag that loads package.js. Try:
<script src="source/package.js" type="text/javascript"> </script>
You haven't supplied Page2 but it appears the code would work as-is.
Here's a fiddle showing the working page: http://jsfiddle.net/kgxvg7Lw/1/
Some thoughts:
1) Are you using a case-sensitive file system? You show app.js but your package.js has App.js (capitalized).
2) Are you certain there are no parse errors in the console?
Now, that said... You probably don't want to reload a new app for every 'page' switch. Usually, you would use something like Panels to allow the app to control the content that appears on the screen and just navigate among the panels as needed.

Resources