CSS Not Linking To HTML Replit - html

I am using replit to host a chat server using Node.js and Socket.io. I used the getting started guide provided by socket.io (https://socket.io/get-started/chat), and saw that the HTML code used internal CSS. I attempted to change this and have the following code:
index.js
const express = require('express');
const app = express();
const http = require('http');
const server = http.createServer(app);
const { Server } = require("socket.io");
const io = new Server(server);
app.get('/', (req, res) => {
res.sendFile(__dirname + '/index.html');
});
io.on('connection', (socket) => {
console.log('a user connected');
socket.on('disconnect', () => {
console.log('user disconnected');
});
});
io.on('connection', (socket) => {
socket.on('chat message', (msg) => {
io.emit('chat message', msg);
});
});
server.listen(3000, () => {
console.log('Site is up and running!');
});
index.html
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<ul id="messages"></ul>
<form id="form" action="">
<input id="input" autocomplete="off" /><button>Send</button>
</form>
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io();
var messages = document.getElementById('messages');
var form = document.getElementById('form');
var input = document.getElementById('input');
form.addEventListener('submit', function(e) {
e.preventDefault();
if (input.value) {
socket.emit('chat message', input.value);
input.value = '';
}
});
socket.on('chat message', function(msg) {
var item = document.createElement('li');
item.textContent = msg;
messages.appendChild(item);
window.scrollTo(0, document.body.scrollHeight);
});
</script>
</body>
</html>
styles.css
body {
margin : 0;
padding-bottom : 3rem;
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
}
#form {
background : rgb(0, 0, 0, 0.15);
padding : 0.25rem;
position : fixed;
bottom : 0;
left : 0;
right : 0;
display : flex;
height : 3rem;
box-sizing : border-box;
backdrop-filter : blur(10px);
}
#input {
border : none;
padding : 0 1rem;
flex-grow : 1;
border-radius : 2rem;
margin : 0.25rem;
}
#input:focus {
outline : none;
}
#form > button {
background : #333;
border : none;
padding : 0 1rem;
margin : 0.25rem;
border-radius : 3px;
outline : none;
color : #fff;
}
#messages {
list-style-type : none;
margin : 0;
padding : 0;
}
#messages > li {
padding : 0.5rem 1rem;
}
#messages > li:nth-child(odd) {
background : #efefef;
}
However, when I run the repl the expected result does not show up and the CSS does not apply to the HTML. Could anyone tell me what is going on?

I think you should use the express.static() method in the index.js file. This method allows us to serve static files. releated documentation
To serve static files such as images, CSS files, and JavaScript files, use the express.static built-in middleware function in Express.
The function signature is:
express.static(root, [options])
The root argument specifies the root directory from which to serve static assets.
For example, use the following code to serve images, CSS files, and
JavaScript files in a directory named public:
app.use(express.static('public'))
Now, you can load the files that are
in the public directory:
http://localhost:3000/images/kitten.jpg
http://localhost:3000/css/style.css http://localhost:3000/js/app.js
http://localhost:3000/images/bg.png http://localhost:3000/hello.html
Express looks up the files relative to the static directory, so the
name of the static directory is not part of the URL. To use multiple
static assets directories, call the express.static middleware function
multiple times:
app.use(express.static('public'))`
app.use(express.static('files'))
Express looks up the files in the order in which you set the static
directories with the express.static middleware function.

Related

How to disable 'Let site view files?' message (when running locally)

I am looking for a way to disable the popup message which shows when using window.showDirectoryPicker. This page is served from localhost via WebView2 component in a WPF app.
<!DOCTYPE html>
<html>
<body>
<div class="fl" style="margin: 0 0 2rem 0"><button id="addToFolder">Give access to folder</button></div>
</body>
</html>
<script>
let directory;
document.getElementById('addToFolder').addEventListener('click', async () => {
try {
directory = await window.showDirectoryPicker({
startIn: 'desktop'
});
for await (const entry of directory.values()) {
let newEl = document.createElement('div');
newEl.innerHTML = `<strong>${entry.name}</strong> - ${entry.kind}`;
document.getElementById('folder-info').append(newEl);
}
} catch (e) {
console.log(e);
}
});
</script>
Note that I already have full file system access via the WPF app, so its not a security concern.

contentDocument is null even when iframe is loaded while using React

I am attempting to make changes to a document inside of an iframe from its parent. Yes, I know this is bad practice, but I've exhausted all of my other options for doing this in a sane way. Unfortunately I've run into a problem where the "contentDocument" property on the iframe is always null, even after a "load" event completes. What am I missing?
Code:
import {useCallback, useEffect, useRef} from "react";
export function MyIframeComponent(): JSX.Element {
const iframeFref = useRef<HTMLIFrameElement>(null);
const myUrl = "/url/to/be/framed";
const onLoadCallback = useCallback(() => {
if (!iframeFref.current) {
console.log("Current is null after load") // doesnt fail here
return;
}
console.log(iframeFref.current) // I'm a valid iframe with children!
console.log(iframeFref.current.contentWindow) // I'm a valid window!
console.log(iframeFref.current.contentEditable) // I'm ... "inherit"?
console.log(iframeFref.current.contentDocument) // I'm null!
if (iframeFref.current.contentDocument) {
console.log("Success! I can do stuff")
} else {
console.log("Failure! I'm mysterious")
}
}, []);
useEffect(() => {
if (iframeFref.current) {
iframeFref.current.addEventListener("load", onLoadCallback);
}
return () => {
if (iframeFref.current) {
iframeFref.current.removeEventListener("load", onLoadCallback);
}
}
}, [iframeFref, onLoadCallback]);
return <iframe ref={iframeFref} src={myUrl} />
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

Open Dialogbox with Jquery

I am trying to open up a website(Google DialogFlow Chat BOT) in my website using JQuery load function.
My Code is as shown below.
ChatBOT
<div id="configs-dialog" title="ChatBOT">
</div>
$("#configs").ready( function() {
$( "div#configs-dialog" ).dialog({
autoOpen: false,
height: 400,
width: 600,
modal: true,
buttons: {
Close: function() {
$( this ).dialog( "close" );
}
}
});
<!-- On Click function for terms dialog -->
$('#configs').click(function(){ $('div#configs-dialog').dialog('open'); });
} );
<!-- load configs html -->
$(function(){
$("#configs-dialog").load("https://console.dialogflow.com/api-client/demo/embedded/bbdd7d51-741c-4308-82c0-fc70073b057e");
});
I am not able to load the website into the dialog window.
It opens up a blank dialog box when I click on the link.
Can any one please help me with this?
With this sort of element, you cannot use .load() as it will only load the elements and not the JavaScript that is needed.
When calling .load() using a URL without a suffixed selector expression, the content is passed to .html() prior to scripts being removed. This executes the script blocks before they are discarded. If .load() is called with a selector expression appended to the URL, however, the scripts are stripped out prior to the DOM being updated, and thus are not executed.
Due to browser security restrictions, most "Ajax" requests are subject to the same origin policy; the request can not successfully retrieve data from a different domain, subdomain, port, or protocol.
Consider using an iFrame instead.
$(function() {
$("#configs-dialog").dialog({
autoOpen: false,
height: 400,
width: 600,
modal: true,
buttons: [{
text: "Close",
class: "ui-state-primary",
click: function(e) {
var results = confirm("Are you sure you want to close the ChatBOT?");
if (results) {
$(this).dialog("close");
}
return false;
}
}]
});
$('#configs').click(function() {
$('#configs-dialog').dialog('open');
$("#configs-dialog")
.html("")
.append($("<iframe>", {
class: "configs-dialog-frame",
src: "https://console.dialogflow.com/api-client/demo/embedded/bbdd7d51-741c-4308-82c0-fc70073b057e"
})
.css("height", $("#configs-dialog").height() - 5));
});
});
.ui-dialog .ui-dialog-titlebar {
display: none;
}
.ui-dialog #configs-dialog.ui-dialog-content {
padding: 0;
}
.configs-dialog-frame {
border: 0;
width: 100%;
margin: 0;
padding: 0;
}
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
ChatBOT
<div id="configs-dialog" title="ChatBOT"></div>

Adding Header to Each Page of PDF in Node Puppeteer

I am trying to print a header section to each page of a PDF that gets generated. I'm also using pdf-merger to merge together multiple PDFs. Right now when I execute this code the PDF generated contains multiple documents, as expected. However the Header section I'm adding only seems to show up in the 2nd and 5th of the documents that are part of the full PDF. I cannot tell from looking at my code why that is happening. I would assume the Header would be added to each of the documents.
First question: why am I noticing the behavior I am. Understand that would help me know what to adjust. Second question: How can I adjust this code so that the Header is added to each of the pages of the document?
Here is the section where I pass options to page.pdf():
let doc = await page.pdf({
displayHeaderFooter: true,
format: "A4",
printBackground: true,
headerTemplate: '<span style="font-size: 30px; width: 50px; height: 50px; color:black; margin: 20px;">Header</span>',
});
And here is the full block of code:
let merger = new PDFMerger();
const browser = await puppeteer.launch();
const page = await browser.newPage();
let recordNum = 1;
for (let r of recordsArr) {
try {
let signatures = [];
signatures = await signatureService.getSignatures({}, [r.guid]);
if (signatures.length) r.signatureBase64Str = signatures[0].value;
} catch (err) {
console.log(err);
return Response.Failure("Error occurred while obtaining signature.", err);
}
r.logoBase64Str = base64Logo;
if (r.goalNotes.length) {
for (const [i, value] of r.goalNotes.entries()) {
value.number = i + 1;
}
}
try {
console.log(`processing record ${recordNum} of ${recordsArr.length}`);
const content = await compile(r);
await page.setContent(content);
await page.emulateMediaType("screen");
let doc = await page.pdf({
displayHeaderFooter: true,
format: "A4",
printBackground: true,
headerTemplate: '<span style="font-size: 30px; width: 50px; height: 50px; color:black; margin: 20px;">Header</span>',
});
merger.add(doc);
++recordNum;
} catch (error) {
console.log(error);
return Response.Failure("Unable to generate PDF by parameters passed.");
}
}
It's hard to tell what's wrong with your code since so many functions are undefined, but here's a minimal, runnable example that adds headers to all pages using the same PDF merger package as you:
const PDFMerger = require("pdf-merger-js");
const puppeteer = require("puppeteer");
const headerTemplate = `<span style="font-size: 30px; width: 200px; height: 200px; background-color: black; color: white; margin: 20px;">Header</span>`;
const mockContent = Array(10).fill().map((_, i) => `<div>page ${i}</div>`);
const filename = "merged.pdf";
const pdfSettings = {
displayHeaderFooter: true,
format: "A4",
printBackground: true,
headerTemplate,
margin: {top: "100px", bottom: "100px"},
};
let browser;
(async () => {
browser = await puppeteer.launch();
const [page] = await browser.pages();
const merger = new PDFMerger();
for (const content of mockContent) {
await page.setContent(content);
merger.add(await page.pdf(pdfSettings));
}
await merger.save(filename);
})()
.catch(err => console.error(err))
.finally(async () => await browser.close())
;

how to authenticate myself asynchronously on the Google Drive API using AngularJS and HTML

Could someone determine how to authenticate myself asynchronously on the Google Drive API using AngularJS and HTML?
I am getting stuck on the call to gapi.auth.authorize because the callback function never gets called:
Here is the AngularJS--HTML5 code excerpt which does not work currently,
var app = angular.module('myApp', []);
app.service('googleService', ['$http', '$rootScope', '$q', function ($http, $rootScope, $q) {
this.login = function () {
gapi.auth.authorize(
{ client_id: '1009536034660-armd84ckoemm3jan35ceupjhdsmo0fa1.apps.googleusercontent.com', scope: 'https://www.googleapis.com/auth/plus.login https://www.googleapis.com/auth/userinfo.email' , immediate: true },
this.handleAuthResult);
return deferred.promise;
}
this.handleClientLoad = function {
gapi.client.setApiKey(apiKey);
gapi.auth.init(function () { });
window.setTimeout(checkAuth, 1);
};
this.checkAuth = function () {
gapi.auth.authorize({
client_id: clientId,
scope: scopes,
immediate: true,
hd: domain
}, this.handleAuthResult);
};
this.handleAuthResult = function (authResult) {
if (authResult && !authResult.error) {
var data = {};
gapi.client.load('oauth2', 'v2', function () {
var request = gapi.client.oauth2.userinfo.get();
request.execute(function (resp) {
data.email = resp.email;
deferred.resolve(data);
});
});
} else {
deferred.reject('error');
}
};
this.handleAuthClick = function (event) {
gapi.auth.authorize({
client_id: clientId,
scope: scopes,
immediate: false,
hd: domain
}, this.handleAuthResult);
return false;
};
}]);
app.controller('myController', ['$scope', 'googleService', function ($scope, googleService) {
$scope.login = function () {
$scope.login = function () {
googleService.login().then(function (greeting) {
console.log('Success: ' + greeting);
}, function (reason) {
console.log('Failed: ' + reason);
}, function (update) {
console.log('Got notification: ' + update);
});
};
};
}]);
} else {
deferred.reject('error');
}
};
});
Why is the gapi.auth.authorize failing to call the callback?
First I checked this hypothesis stackoverflow.com/questions/20036893/… and it was incorrect. Next I checked this hypothesis : stackoverflow.com/questions/31659414/… and it was also wrong.
I even tried using Brendan's SetTimeout workaround in this URL, https://groups.google.com/forum/#!topic/google-api-javascript-client/GuFxPzqQ9-0 and it did not function properly.
In addition, I requested and obtained a new OAuth2 client id with the correct javascript origin. Evidently , the onload callback is only called after successful loading of the script. Or, is there a timeout possibility for the callback to be invoked?
Here is Windows 7 ASP.NET program written entirely in Javascript and HTML which works properly :
<html>
<head>
<title>Google+ Sign-in button demo: rendering with JavaScript</title>
<style type="text/css">
html, body { margin: 0; padding:0;}
#signin-button {
padding: 5px;
}
#oauth2-results pre { margin: 0; padding:0; width: 600px;}
.hide { display: none;}
.show { display: block;}
</style>
<script src="https://apis.google.com/js/client:platform.js" type="text/javascript"></script>
<script type="text/javascript">
var loginFinished = function (authResult) {
if (authResult) {
console.log(authResult);
}
gapi.client.load('oauth2', 'v2', function () {
gapi.client.oauth2.userinfo.get()
.execute(function (resp) {
// Shows user email
console.log(resp.email);
});
});
};
var options = {
'callback': loginFinished,
'approvalprompt': 'force',
'clientid': '375218714272ao7690jhv6sk7jphi0jf3l5t500sajvt.apps.googleusercontent.com',
'scopes': ['https://www.googleapis.com/auth/drive.metadata.readonly', 'https://www.googleapis.com/auth/drive.readonly'],
'requestvisibleactions': 'http://schemas.google.com/CommentActivity http://schemas.google.com/ReviewActivity',
'cookiepolicy': 'single_host_origin'
};
var renderBtn = function () {
gapi.signin.render('renderMe', options);
}
</script>
</head>
<body onload ="renderBtn()">
<div id="renderMe"></div>
</body>
</html>
Could I ask why the Windows 7 ASP.NET Javascript code works okay but not the AngularJS code version?
You have to point $window.location.href at a file in the Windows filesytem which conforms to JavaScript origin naming convention.