Snabbdom - Not able to load javascript file into snabbdom project - javascript

I want to embed a web-component based javascript file into the snabbdom based project but not able to load it into the project.
Also not able to find that particular javascript file in the dist folder after building the project.
const view = (state, {updateState}) => {
function AddLibrary(urlOfTheLibrary) {
console.log("add librar",urlOfTheLibrary);
const script = document.createElement('script');
script.src = urlOfTheLibrary;
document.head.appendChild(script);
}
return (
<div>
<div>Hello</div>
<sg-bar hook-init={AddLibrary("/sg-bar.js")}></sg-bar>
</div>
);
};

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

Use imported script inside development build of Vue

I'm currently building an application and, and I applied vue 3 only in one page via script.
<script src="https://unpkg.com/jspdf#latest/dist/jspdf.umd.min.js"></script>
<script src="https://unpkg.com/vue#3"></script>
I'm trying to use the imported module (jsPdf) via a script, and it is not working.
methods: {
generateReport() {
let pdfName = 'test';
var doc = new jsPDF();
doc.text("Hello World", 10, 10);
doc.save(pdfName + '.pdf');
}
}
This is the error when I'm trying to do the method above:
Uncaught ReferenceError: jsPDF is not defined
Is it possible to use the module imported using script in the development build of Vue? or is there any other way to generate pdf without importing scripts?
Try like following snippet
const { jsPDF } = jspdf
const app = Vue.createApp({
el: "#demo",
methods: {
generateReport() {
let pdfName = 'test';
var doc = new jsPDF();
doc.text("Hello World", 10, 10);
doc.save(pdfName + '.pdf');
console.log(doc)
}
}
})
app.mount('#demo')
<script src="https://unpkg.com/jspdf#latest/dist/jspdf.umd.min.js"></script>
<script src="https://unpkg.com/vue#3"></script>
<div id="demo">
<button #click="generateReport">pdf</button>
</div>
Have you imported the library in the .vue file you are trying to use it in?
import { jsPDF } from "jspdf";

Google Scripts/HTML/JavaScript Upload File to Folder Error Argument cannot be null: blob

I am creating an online HTML form that gives people the option to upload a file. I am using google sheets to collect the data so I am using their google scripts feature. When I run my code everything works, meaning I get data inserted into cells, but not the file upload. Here is my Google Scripts code for the file upload:
function doGet(request) {
return HtmlService.createTemplateFromFile('Index')
.evaluate();
}
/* #Include JavaScript and CSS Files */
function include(filename) {
return HtmlService.createHtmlOutputFromFile(filename)
.getContent();
}
function uploadFiles(data){
var folder = DriveApp.getFolderById('1pp1ELzGa2fZqU4IHAasZMHsmYx19pnYv');
var createFile = folder.createFile(data.image);
return createFile.getUrl();
}
From what I can tell the problem is at the data.image. This is where I am trying to retrieve my image so I can upload it into the folder. It must be that uploadFiles(data) is not properly bringing in data.
Here is the HTML and JavaScript:
<form id="myForm" onsubmit="handleFormSubmit(this)">
<h1 class="h4 mb-4 text-center" style="text-align:center"> <center>File Upload Testing</center></h1>
<table>
<tr>
<td colspan="11"><input type="file" id="image"></td>
</tr>
<input type="hidden" id="fileURL" name="fileURL">
</table>
<button type="submit" class="button button1" id="submitBtn">Submit</button>
</form>
<script>
document.getElementById('submitBtn').addEventListener('click',
function(e){
google.script.run.withSuccessHandler(onSuccess).uploadFiles(this.parentNode);;}
)
function onSuccess(data){
document.getElementById("fileURL").value = data;
}
</script>
I have a feeling that the e parameter is not retrieving the data above, however I don't really understand how it works. It could also be this.parentNode that's not grabbing the fike.
I am using the onSuccess function to retrieve the link so I can put it into my google sheet for quick access.
This is the error I receive;
Here is a link to the google sheet. To reach google scripts go to 'Tools -> Script Editor'.
https://docs.google.com/spreadsheets/d/16w8uB4OZHCeD7cvlrUv5GHP72CWxQhO1AAkF9MMSpoE/edit?usp=sharing
Here is another technique I attempted to use:
Javascript:
function uploadthis(fileForm){
const file = fileForm.image.files[0];
const fr = new FileReader();
fr.onload = function(e) {
const obj = {
// filename: file.name
mimeType: file.type,
bytes: [...new Int8Array(e.target.result)]
};
google.script.run.withSuccessHandler((e) => console.log(e)).uploadFiles(obj);
};
fr.readAsArrayBuffer(file);
}
Google Script:
function uploadFiles(data){
var file = Utilities.newBlob(data.bytes, data.mimeType); // Modified
var folder = DriveApp.getFolderById('1pp1ELzGa2fZqU4IHAasZMHsmYx19pnYv');
var createFile = folder.createFile(file);
return createFile.getId(); // Added
}
Thank you!

How do I insert an HTML Script embed into React?

I am trying to get an eCommerce html script embed to work in React, by having it render from a component.
An example below:
<div data-embed="store">
<script type="application/json">
{"some json text"}
</script>
</div>
<script async src="https://website.com/loader.js"></script>
From what I have been able to gather, I can use the useEffect hook, but have not been able to get it to work correctly.
You can do this in useEffect by creating a script element, adding the src and async attribute and appening it to the document body. You would then have the imported JS available globally.
EDIT:
The same can be applied to JSON with exception of having to load it in manually.
const [json, setJson] = useState(null);
useEffect(() => {
const script = document.createElement('script');
script.src = "https://website.com/loader.js";
script.async = true;
document.body.appendChild(script);
// json
const jsonScript = document.createElement('script');
jsonScript.innerHTML = `
{
"greeting": "hello"
}
`;
jsonScript.id = 'json';
jsonScript.type = 'application/json';
document.body.appendChild(jsonScript);
setJson(JSON.parse(document.getElementById('json').innerHTML));
}, []);

Add AngularJS files while loading

So I'm trying to load all the AngularJS scripts which I need in my app when the index.html file loads.
For this I've made this piece of code
<head>
...
AngularJS libaries loads
...
<script>
var main = {
root: [
'core.js'
]
};
var iterateScripts = function(folder, path){
for(var key in folder){
if(key.toLowerCase() === 'root'){
for(var i = 0; i < folder[key].length; i++){
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = path + '/' + folder[key][i];
// console.info('script : '+ script.src)
document.getElementsByTagName('head')[0].appendChild(script);
}
} else {
var newPath = path + '/' + key;
// console.info('path : ', newPath, folder[key])
iterateScripts(folder[key], newPath);
}
}
};
iterateScripts(main, 'app/main');
console.info(document.getElementsByTagName('head')[0])
</script>
</head>
This loads the files okay, but I get this error
AngularJS error explanation
After testing back and forth I've concluded that the problem is because the page loads while AngularJS is compiling, which creates the error.
If this is true, how can I load my angular app in a similar fashion before the body tag loads?
You'll have to bootstrap angular yourself instead of using ng-app. Here is the documentation on it: https://docs.angularjs.org/guide/bootstrap.
Once all your scripts are finished loading then you'll run a piece of code that looks similar to this:
angular.element(document).ready(function() {
angular.bootstrap(document, ['myApp']);
});
Which tells angular it is ready to start.

Categories