correct javasript code execution in flask - javascript

I tried to use click on button:
#app.route("/")
def test_edition_open():
return render_template("index.html")
my index.html file is:
<script type="text/javascript" src="{{ url_for('static', filename='script.js') }}"></script>
The main part is just two buttons:
<div class = "counter">
<button class = "minus">-</button>
<div class = "result">1</div>
<button class = "plus">+</button>
</div>
I tried to make My script.js file work in flask. The code is very simple, it should add numbers by clicking on button:
const plus = document.querySelectorAll('.plus');
const minus = document.querySelectorAll('.minus');
const result = document.querySelectorAll('.result');
function min()
{
return function (ev)
{
if (ev.target.nextElementSibling.innerHTML > 0)
{
return --ev.target.nextElementSibling.innerHTML;
}
}
}
function pl()
{
return function (ev)
{
return ++ev.target.previousElementSibling.innerHTML;
}
}
minus.forEach(function (dominus)
{
dominus.addEventListener('click', min());
})
plus.forEach(function (doplus)
{
doplus.addEventListener('click', pl());
})
In https://playcode.io this code worked well. How should I solve this problem?

Make sure that script file successfully connected to html file. to check this add console.log("File Connected") in your script.js file. Then open your browser console to check that console message is logged correctly. If not then try to linked your static file correctly. How to set static_url_path in Flask application
Or you can put your Javascript code in html file using script tag.
Something like this:
<script> your javascript code here</script>

Related

Modify script to get sheet folder ID

I would like some help to modify this script here: Upload multiple large files to Google Drive using Google Apps Script
The question is the following: this script uploads to a folder within the folder defined in const uploadParentFolderId = "1cOe4ZXjBUZHgPwADg1QRpUzcQqGxON_4"; which is in the forms.html file, the problem is that I intend to call this script within a spreadsheet through an html alert and I would like that the file was uploaded inside a folder of the spreadsheet folder, that is, the script would need to get the ID of the spreadsheet folder.
Javascript is a language that is a little out of my daily life, but I'm trying to learn it on my own...
If anyone can give me a light on this, it will be of great help!
EDIT:
I tried this:
var ssid = SpreadsheetApp.getActiveSpreadsheet().getId();
var AllFolders = DriveApp.getFileById(ssid).getParents();
var ChildFolderTest;
if (AllFolders.hasNext()) {
ChildFolderTest = AllFolders.next();
var FinalFolderID = ChildFolderTest.getId();
}
const chunkSize = 5242880;
const uploadParentFolderId = FinalFolderID; // creates a folder inside of this folder
But for some reason it doesn't work, the upload doesn't start.
Any idea how to resolve?
Here is an example of how to get the spreadsheet folder id.
form.html
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<input id="uploadParentFolderId" type="text">
<br>
<input id="getFolderButton" type="button" onclick="getFolderButtonClick()" value="Get Folder">
<script>
function getFolderButtonClick() {
try {
google.script.run.withSuccessHandler(
function(folder) {
document.getElementById("uploadParentFolderId").value = folder;
}
).getFolder();
}
catch(err) {
alert(err);
}
}
</script>
</body>
</html>
Code.gs
function getFolder() {
try {
let spread = SpreadsheetApp.getActiveSpreadsheet();
let file = DriveApp.getFileById(spread.getId());
let folders = file.getParents();
return folders.next().getId();
}
catch(err) {
throw "Error in test: "+err;
}
}
Reference
google.script.run.withSuccessHandler()
Another way to do this is via a printing scriptlet. You can use HTML templates which will output data from your server functions and print it to the HTML file.
Based on the script you found you can first change the declaration of the folder const on the forms.html file:
const uploadParentFolderId = <?=getParent()?>; // creates a folder inside of this folder
As explained in the docs, the <?= ... ?> tags indicate that the output from the getParent() function will be printed to the HTML file.
Then create getParent() on the Code.gs file to return the ID of the sheet's parent folder:
function getParent(){
var ss = SpreadsheetApp.getActiveSpreadsheet()
var id = ss.getId()
var parent = DriveApp.getFileById(id).getParents().next().getId()
return parent
}
Finally change the doGet() function on the Code.gs file to use a template instead of just printing the HTML file, this is so the <?=?> tags can be interpreted before outputting the page:
function doGet(e) {
return HtmlService.createTemplateFromFile('forms.html').evaluate();
}
I just modified this from the script and was able to create the new folder in the same location as the Spreadsheet.
Reference:
HTML Templates

Script trying to define a function from the wrong file

I want to call a function 'addArray' in a separate .js file called 'main.js'
When I run this code, I get an error saying the 'addArray' is not defined in checkout.js
I don't want it to look for the function in checkout.js, I want it to look for the function in main.js
I am using node.js
<body onload="myFunction()">
<script src = "https://www.paypalobjects.com/api/checkout.js"></script>
<script type = "text/javascript" src = "main.js"></script>
<div class="container">
</div>
<script>
paypal.Button.render(
{
onAuthorize: function(data, actions)
{
return actions.payment.execute().then(function()
{
// Show a confirmation message to the buyer
days = 30
localStorage.setItem("days", days);
inputDays = JSON.parse(localStorage.getItem('days'));
inputName = localStorage.getItem('name');
window.alert('Thank you for your purchase!');
console.log(inputDays);
console.log(inputName);
addArray();
});
}
}, '#paypal-button');
I had to delete most of the intermediate non essential code for the purpose of submitting this question
So... There are a few things I think you should check for.
If you are using commonJS, be sure that you are exporting the addArray function like so: module.exports = {addArray}; Then require it from your main.js file.
If you are using es6 syntax, you can export it like export default addArray or export {addArray}, then import it in your main.js file using the import {addArray} from... or import addArray from ... depending on the export style you used.

Import and export issue Javascript (No node.js)

Hello !
I tried using import/exports for the first time, and I have this issue in my code :
The requested module '../Ajout/script.js' does not provide an export named 'flagMap'
I have these files Supprimer.js, containing at the first line :
import{flagMap, findUrl, createUrl,texteValide} from '../Ajout/script.js';
And in Ajout.js contained in another forlder in the parent folder:
var flagMap={/*really long map*/}
function findUrl(isoCode){/*long url finder*/}
function createUrl(svgUrl) {
return `https://upload.wikimedia.org/wikipedia/${svgUrl}`;
}
function texteValide(element){/*text validation for a form*/}
export{flagMap,findUrl,createUrl,texteValide};
/*
other non-exported functions
*/
There is the type="module" in my html when I'm importing the script, and my Ajout.js also contains other functions, maybe it's causing issues ?
Also : The issue is not only flagMap but every import, because it shows another file if I remove flagMap from the imports
This works fine for me:
<!-- index.html -->
<html>
<head> ... </head>
<body>
<script type="module" src="path/to/Supprimer.js"></script>
</body>
</html>
// Ajout.js
var flagMap = {
// ...
};
function findUrl(isoCode) {
// ...
}
function createUrl(svgUrl) {
// ...
}
function textValide(element) {
// ...
}
// Export functions and variables
export {
flagMap,
findUrl,
createUrl,
texteValide
};
// Supprimer.js
import { flagMap, findUrl } from "path/to/Ajouter.js";
console.log(flagMap); // Prints map
findUrl("EN"); // Can call function

Chrome Extension to pull text from script

I'm attempting to pull "webId%22:%22" var string from a script tag using JS for a Chrome extension. The example I'm currently working with allows me to pull the page title.
// payload.js
chrome.runtime.sendMessage(document.title);
// popup.js
window.addEventListener('load', function (evt) {
chrome.extension.getBackgroundPage().chrome.tabs.executeScript(null, {
file: 'payload.js'
});;
});
// Listen to messages from the payload.js script and write to popout.html
chrome.runtime.onMessage.addListener(function (message) {
document.getElementById('pagetitle').innerHTML = message;
});
//HTML popup
<!doctype html>
<html>
<head>
<title>WebID</title>
<script src="popup.js"></script>
<script src="testButton.js"></script>
</head>
<body>
<button onclick="myFunction()">Try it</button>
<p id="body"></p>
<h3>It's working</h1>
<p id='pagetitle'>This is where the webID would be if I could get this stupid thing to work.</p>
</body>
</html>
What I am trying to pull is the webID from below:
<script if="inlineJs">;(function() { window.hydra = {}; hydra.state =
JSON.parse(decodeURI("%7B%22cache%22:%7B%22Co.context.configCtx%22:%7B%22webId%22:%22gmps-salvadore%22,%22locale%22:%22en_US%22,%22version%22:%22LIVE%22,%22page%22:%22HomePage%22,%22secureSiteId%22:%22b382ca78958d10048eda00145edef68b%22%7D,%22features%22:%7B%22directivePerfSwitch%22:true,%22enable.directive.localisation%22:true,%22enable.directive.thumbnailGallery%22:true,%22enable.new.newstaticmap%22:false,%22disable.forms.webId%22:false,%22use.hydra.popup.title.override.via.url%22:true,%22enable.directive.geoloc.enableHighAccuracy%22:true,%22use.hydra.theme.service%22:true,%22disable.ajax.options.contentType%22:false,%22dealerLocator.map.use.markerClustering%22:true,%22hydra.open.login.popup.on.cs.click%22:false,%22hydra.consumerlogin.use.secure.cookie%22:true,%22use.hydra.directive.vertical.thumbnailGallery.onpopup%22:true,%22hydra.encrypt.data.to.login.service%22:true,%22disable.dealerlocator.fix.loading%22:false,%22use.hydra.date.formatting%22:true,%22use.hydra.optimized.style.directive.updates%22:false,%22hydra.click.pmp.button.on.myaccount.page%22:true,%22use.hydra.fix.invalid.combination.of.filters%22:true,%22disable.vsr.view.from.preference%22:false%7D%7D,%22store%22:%7B%22properties%22:%7B%22routePrefix%22:%22/hydra-graph%22%7D%7D%7D")); }());</script>
You have inline code in onclick attribute which won't work, see this answer.
You can see an error message in devtools console for the popup: right-click it, then "Inspect".
The simplest solution is to attach a click listener in your popup.js file.
The popup is an extension page and thus it can access chrome.tabs.executeScript directly without chrome.extension.getBackgroundPage(), just don't forget to add the necessary permissions in manifest.json, preferably "activeTab".
For such a simple data extraction you don't even need a separate content script file or messaging, just provide code string in executeScript.
chrome.tabs.executeScript({
code: '(' + (() => {
for (const el of document.querySelectorAll('script[if="inlineJs"]')) {
const m = el.textContent.match(/"([^"]*%22webId%22[^"]*)"/);
if (m) return m[1];
}
}) + ')()',
}, results => {
if (!chrome.runtime.lastError && results) {
document.querySelector('p').textContent = decodeURI(results[0]);
}
});

Recaptcha.create works locally but not on server

I've got an Google Recaptcha it uses the Recaptcha.create. However for some reason the Recaptcha.create works locally but not on the server. Here is my html and js.
HTML
<script type="text/javascript" src="http://www.google.com/recaptcha/api/js/recaptcha_ajax.js"></script>
<div id="recaptcha"></div>
<div id="fError">Waiting for input.</div>
<script src="/assets/js/upload-flash.js"></script>
And this is the upload-flash.js
var captchaused = false;
function showRecaptcha() {
Recaptcha.create("6LfHYvgSAAAAAJ9G7fNYW5vwQkxUZDNSFhweiOPp", "recaptcha", {
theme: "clean",
callback: Recaptcha.focus_response_field});
}
function fileSelected() {
var file = document.getElementById('fileToUpload').files[0];
if (file) {
if(captchaused === false){
captchaused = true;
showRecaptcha();
} else {
Recaptcha.reload();
}
}
}
/*... and after this comes the uploading part. Removed it so that it doesn't become too long*/
Here are pictures
Local
Server
I made a mistake with the public and private keys I get from google and used the wrong ones. After changing the keys I used it started working perfectly again.

Categories