Submitting data from contentscript input to firebase - firebase

I am making a chrome extension with a custom popup that comes up after the page is loaded.
I would like to safe the submitted answers from the input-field to my firebase database, so that i cant include them in another website. It all works, but the problem is, that the answers from the extension get blocked:
Cross-Origin Read Blocking (CORB) blocked cross-origin response with MIME type text/plain. See for more details.
How can i solve this Problem?
Note: I am not a pro at this, so i'd really appreciate an easy to follow solution:)
these are my steps:
I downloaded the firebase.js and added it to my manifest.json:
"matches": ["<all_urls>"],
"js": [ "Libraries/firebase-app.js",
"Libraries/firebase-firestore.js",
"sketch.js"],
I injected the html to the webpage using the content-script:
<div id="bg-modal">
<div class="modal-content">
<button class="close">+</button>
<div class="text"></div>
<form class="antwortfeld antwortfeld1" action="">
<textarea type="text" name="antwort" placeholder="Antworten"></textarea>
<button class="Senden">Senden</button>
</form>
I added the firebase app configuration and initialized firebase in the content-script
// Your web app's Firebase configuration
var firebaseConfig = {
apiKey: "...TRZeHhLQ9gMa4V4gy9WSlQ",
authDomain: "....firebaseapp.com",
databaseURL: "https://....firebaseio.com",
projectId: "....",
storageBucket: "....appspot.com",
messagingSenderId: "...0021",
appId: "1:385077100021:.....ba5a776b4bc"
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
const db = firebase.firestore();
then i added this to the content-script as well to save the inputdata to firebase:
const form1 = document.querySelector('.antwortfeld1');
// saving data
form1.addEventListener('submit', (e) => {
e.preventDefault();
db.collection('Antworten').add({
Antwort1: form1.antwort.value,
})
form1.antwort.value = ' ';
})
As I said, it's all working, but I get blocked. I guess I'll have to use a background-script to get around this? What would that look like?
Any other options?

Related

Consuming external API using SvelteKit works but only after reloading route

Using SvelteKit 1.0.0-next.95 to get a JSON array back from an external API endpoint and display in a template like this:
<script context="module">
export async function load({ fetch }) {
const url = 'https://www.schoolhouseyoga.com/api/announcement'
const res = await fetch(url, {
method: 'GET',
mode: 'cors',
headers: {
'content-type': 'application/json'
}
})
if (res.ok) {
return {
props: {
sections: await res.json()
}
}
}
return {
status: res.status,
error: new Error(`Could not load ${url}`)
}
}
</script>
<script>
export let sections = []
</script>
<template>
<section>
{#if sections.length > 0}
<div class="callout">
<h1>Announcements</h1>
{#each sections as section}
<div>
{#if section.announcements.length > 0}
<h2>{section.section}</h2>
{/if}
{#each section.announcements as announcement}
<p><b>{announcement.title} </b>- {#html announcement.description}</p>
{/each}
</div>
{/each}
</div>
{/if}
</section>
</template>
If you try https://www.schoolhouseyoga.com/api/announcement (CORS) in a browser or using curl, you'll get a JSON array with two elements.
When I run this in dev mode, npm run dev -- --open and navigate to this route on Safari 14.1 (macOS), I get a 500 error and the message, "Origin http://localhost:3000 is not allowed by Access-Control-Allow-Origin." If I try to navigate to that route on Google Chrome, I get a 500 error and "TypeError: Failed to fetch".
But with either browser, if I refresh the page, the data loads successfully. Navigating to a different route then back again, the error reappears.
I am guessing this has to do with SSR but not sure what to do about it.
Any thoughts?
The problem was related to server-side rendering and a CORS issue with the endpoint. When the server-side code performed the fetch, it worked fine. Subsequent fetches were being performed by the client (which ran into the CORS issue).
While the endpoint appeared to have CORS enabled...
import { Router } from 'express';
import cors from 'cors';
import * as controller from './announcement.controller';
const router = Router();
router.get('/', cors(), controller.index);
But the endpoint was also using helmet and needed
app.use(helmet.permittedCrossDomainPolicies());
prior to loading the routes.
Hope this helps others.

please how can l add a runtime option to disable the check or this warning

I am creating a contact form that will display some messages on screen for the user to know that form was submitted successful
but,l am always receiving error message in my git terminal. Below is the error message.
Handlebars: Access has been denied to resolve the property "message" because it is not an "own property" of its parent.
You can add a runtime option to disable the check or this warning:
See https://handlebarsjs.com/api-reference/runtime-options.html#options-to-control-prototype-access for details
Below is server.js and message.handlebars code;
app.post('/contactUs',function(req,res){
console.log(req.body);
//res.send('thanks');
const newMessage = {
fullname: req.body.fullname,
email: req.body.email,
message: req.body.message,
date: new Date()
}
new Message(newMessage).save(function(err, message){
if (err){
throw err;
}else{
Message.find({}).then(function(messages){
if(messages){
res.render('newmessage',{
title: 'Sent',
messages:messages
});
}else{
res.render('noMessage',{
title: 'Not found'
});
}
});
}
});
});
<h1>Thank you for contacting</h1>
{{#each messages}}
<p>{{fullname}}</p>
<p>{{email}}</p>
<p>{{message}}</p>
<small>{{date}}</small>
<hr>
{{else}}
<p>No messages</p>
{{/each}}
<button class="btn btn-success">Contact Again</button>
I'm guessing your doing the same dating app tutorial I am working on. I solved this problem by following the given link: https://handlebarsjs.com/api-reference/runtime-options.html#options-to-control-prototype-access
Then I downloaded the package npm install #handlebars/allow-prototype-access
Then in server.js add:
const express = require('express');
const Handlebars = require('handlebars')
const expressHandlebars = require('express-handlebars');
const {allowInsecurePrototypeAccess} = require('#handlebars/allow-prototype-access')
Scroll down in server.js to app.engine:
// setup view engine
app.engine('handlebars', exphbs({
defaultLayout: 'main',
}));
app.set('view engine', 'handlebars');
Then add: handlebars: allowInsecurePrototypeAccess(Handlebars)
It should look like this:
// setup view engine
app.engine('handlebars', exphbs({
defaultLayout: 'main',
handlebars: allowInsecurePrototypeAccess(Handlebars)
}));
app.set('view engine', 'handlebars');
I hope this helps. Good Luck.
you can add .lean() to your model for example await Basic.findById(result.id).lean()
This may be happening because of the latest version of Handlebars, but this can be solved by adding a dependency to handlebars.
npm i -D handlebars#4.5.0
Just use the exact same version of "express-handlebars" , which was shown in the tutorial. The latest version of handlebars is causing the problem.
Atleast doing this , worked for me.
This worked for me, pretty similar to the first answer:
const express = require('express');
const handlebars = require('handlebars')
const expressHandlebars = require('express-handlebars');
const { allowInsecurePrototypeAccess } = require('#handlebars/allow-prototype-access')
// configuration express for handlebars
app.engine('hbs', expressHandlebars({ extname: 'hbs',
defaultLayout: 'mainLayout',
handlebars: allowInsecurePrototypeAccess(handlebars),
layoutsDir: __dirname + '/views/layouts/' })
);
const Handlebars=require('handlebars')
const {allowInsecurePrototypeAccess} = require('#handlebars/allow-prototype-access')
app.engine('handlebars',exphbs({defaultLayout:'main',
handlebars: allowInsecurePrototypeAccess(Handlebars)
}));
app.set('view engine','handlebars');
this is happening to a new version of express-handlebars module. To fix this pass the following runtime options into handlebars engine configuration.
first of all, type a following command in your terminal and hit enter:
npm install #handlebars/allow-prototype-access
and
npm install handlebars
after that write these code into your server.js file
const Handlebars = require('handlebars')
and
const {allowInsecurePrototypeAccess} = require('#handlebars/allow-prototype-access')
then add this line:
handlebars: allowInsecurePrototypeAccess(Handlebars)
in your setup view engine.
I also faced the same problem while using mongoose with hbs, but I was using async / await instead of promises. So I tried .lean() method
like #Boniface Dennis said that solved my problem.
For more information please checkout link
//the syntax goes like this
const messages = await Messages.find({}).lean();

Ionic App: Firebase Authenticate with using OAuth Provider shows AUTH_DOMAIN instead of Custom Domain

I implemented a Login with Google API following the Firebase Authentication docs (Authenticate Using OAuth Providers with Cordova) Link. However, it shows the Project Default AUTH_DOMAIN. How do I change it to show custom URL?
<universal-links>
<host name="example.page.link" scheme="https" />
<host name="example-app.firebaseapp.com" scheme="https">
<path url="/__/auth/callback"/>
</host>
</universal-links>
Have you set your domain when adding Firebase to your app?
<script src="https://www.gstatic.com/firebasejs/5.8.2/firebase.js"></script>
<script>
// Initialize Firebase
// TODO: Replace with your project's customized code snippet
var config = {
apiKey: "<API_KEY>",
authDomain: "<PROJECT_ID>.firebaseapp.com",
databaseURL: "https://<DATABASE_NAME>.firebaseio.com",
projectId: "<PROJECT_ID>",
storageBucket: "<BUCKET>.appspot.com",
messagingSenderId: "<SENDER_ID>",
};
firebase.initializeApp(config);
</script>
Also, using your own domain is not as easy as it sounds. Check out this post for more info.

Firebase - Issue Setting up Firebase Cloud Messaging

I'm having some difficulty setting up push notifications with my Firebase app. I followed this tutorial to the letter on setting up cloud messaging
I'd like mobile devices to be able to receive notifications, so I add the requestPermssions() function directly to my index.html
<!-- Firebase -->
<script src="https://www.gstatic.com/firebasejs/3.4.0/firebase.js"></script>
<script src="https://www.gstatic.com/firebasejs/3.4.0/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/3.4.0/firebase-auth.js"></script>
<script src="https://www.gstatic.com/firebasejs/3.4.0/firebase-database.js"></script>
<script src="https://www.gstatic.com/firebasejs/3.4.0/firebase-storage.js"></script>
...
...
<script>
var config = {
apiKey: "56sds55hhjh906rwsbghghsd",
authDomain: "app-33aef.firebaseapp.com",
databaseURL: "https://app-33aef.firebaseio.com",
storageBucket: "app-33aef.appspot.com",
messagingSenderId: "43532673275"
};
firebase.initializeApp(config)
const messaging = firebase.messaging();
messaging.requestPermission()
.then(function(){
console.log('Have Permissions!');
return messaging.getToken()
})
.then(function(token){
console.log(token);
})
.catch(function(error){
console.warn('ERROR: ' + error);
})
messaging.onMessage(function(payload){
console.log('onMessage', payload);
})
</script>
However I'm seeing the following TypeError
firebase.messaging is not a function
After scouring the web I've read that you have to use firebase-admin to use the messaging() function. I've tried that as well but then I get an `Unexpected token import' error, but that may just be my project setup...
Does anyone have a solution for this? I feel like I'm going in circles here for something very simple
Well, I feel that this was so obvious that I never would have thought about it.
Include the script tag for firebase messaging (oy vey).
<script src="https://www.gstatic.com/firebasejs/4.2.0/firebase-messaging.js"></script>
It would have been helpful to mention this in the video as many others were stumped as well

Firebase Authentication from Google App Script?

I'm trying to add firebase authentication to my google doc add on. My goal is to have a sidebar that displays data from my database after authentication. I get the most confused by other answers because I'm unsure about what goes in the html file verse what goes in the google app script file. I know I'm supposed to create a token but after I copy and paste that code from the tutorial I get lost.
Groups/Answers that were partly helpful:
https://groups.google.com/forum/#!topic/firebase-talk/-RKpHaMPTYQ
Google Authentication with Google Spread Sheet via App Script
https://sites.google.com/site/scriptsexamples/new-connectors-to-google-services/firebase/tutorials/using-secured-client-authentication-for-real-time-read-and-write-calls
app.html
<html lang="en">
<head>
<script src="https://www.gstatic.com/firebasejs/3.7.3/firebase.js"></script>
<script>
var config = {
apiKey: "",
authDomain: "",
databaseURL: "",
storageBucket: "",
messagingSenderId: ""
};
firebase.initializeApp(config);
</script>
</head>
<body>
<div id="databaseDiv"></div>
</body>
</html>
Code.gs
/**
* Creates a menu entry in the Google Docs UI when the document is opened.
* This method is only used by the regular add-on, and is never called by
* the mobile add-on version.
*
* #param {object} e The event parameter for a simple onOpen trigger. To
* determine which authorization mode (ScriptApp.AuthMode) the trigger is
* running in, inspect e.authMode.
*/
function onOpen(e) {
DocumentApp.getUi().createAddonMenu()
.addItem('Start', 'showSidebar')
.addToUi();
}
function onInstall(e) {
onOpen(e);
}
function showSidebar() {
var ui = HtmlService.createHtmlOutputFromFile('app')
.setTitle('Sow Google Docs');
DocumentApp.getUi().showSidebar(ui);
}
function makeToken(){
var firebaseUrl = "https://example.firebaseio.com/";
var secret = "EXAMPLEKEYYEKELPMAXE";
var base = FirebaseApp.getDatabaseByUrl(firebaseUrl, secret);
var token = base.createAuthToken(Session.getActiveUser().getEmail());
return token;
}
What am I missing?
Do not use any custom firebase library for apps script, use the Official Firebase Inline Javascript Libraries to achieve your objectives. If you run into problems ask your questions here (but do not be clueless), people will help.

Resources