How to use requirejs on your client side code - html

So recently I was making a website and I added a login page. I wanted to check if the username and password entered existed in the database and if not it would give an alert saying invalid username or password. My code is:
<form>
<label>Enter Username:</label>
<input type="text" id="username">
<br>
<label>Enter Password:</label>
<input type="password" id="password">
<br>
<input type="submit" onclick="submitLoginInfo()">
</form>
and the js is
const { LoginSchemaModel } = require('./dbconfig.js')
// import { LoginSchemaModel } from './dbconfig'
requirejs()
function submitLoginInfo () {
let usernameElement = document.querySelector('#username')
let passwordElement = document.querySelector('#password')
console.log(`Username Element is HTMLElement: ${usernameElement instanceof HTMLElement}`);
console.log(`Username Element is HTMLElement: ${passwordElement instanceof HTMLElement}`);
alert(`usernameElement = ${usernameElement}`);
alert(`passwordElement = ${passwordElement}`);
alert(`username = ${usernameElement.value}`);
alert(`password = ${passwordElement.value}`);
}
Now the problem is with the require because that is not supported. So I decided to use imports instead and added "type"="module" to my package.json but was still getting an error in the console saying I can't use it. Then I used requirejs and ran into this issue where I couldn't import requirejs without using the require function. When I tried to add
var requirejs = require('requirejs')
requirejs.config({
nodeRequire: require
});
it would say that I couldn't use require(). When I tried to do it in a seperate file I realized I had to require that file to use requirejs which wouldn't work. I have no idea on how to fix this, I have been searching stack overflow and other websites but nothing mentions this. I want to know if there is a different way which I have just been missing this whole time.

I will assume that you are just declaring the js in some HTML with a script that will run in the client. Like that <script src="./myscript.js"></script>
Why you couldn't use require
require is the way we import modules in Node.js(an engine that runs javascript outside the browser) or any other javascript engine that adopts the CommonJs modules pattern. Browsers uses what is called ESModules.
Why did changing type="module" in package.json didn't solve this problem?
The package.json file is completely ignored by the browser, it doesn't affect anything in the javascript you import from the script tag. package.json is file used by node.js(and other engines). And type="module" is used in Node.js to use import instead of require, so wouldn't fix even if the browser read it.
How can we import things in browser javascript
Firstly I have to say that browsers usually expect people to use some bundling tool like webpack. (bundler is just a program that transforms all your .js files into a single .js file) instead of importing modules directly, but if you want to do it only using a web-browser and nothing more you can:
Add the type="module" in the script tag.
<script type="module" src="./myscript.js"></script>
Use something like the live server extension of vscode
Because, browsers cannot give .html files to have full access to your files, so you need to simulate a server in a folder.
So now you can simple use import {thing} from "./myscript.js" that will work.
How to use the require.js lib in the browser.
I have to say that you shouldn't use it, it is used by people that want some packages made for node.js to work on browser. But if one would want to use requires only using the browser they would have to remember that when we do npm i requirejs it creates downloads it into the node_modules folder, so we would have to import from there. But again, you shouldn't do that to solve your problem. Stick to the import.

Related

how to export variables from svelte:head to the html section?

Rationale
I'm making a small website using svelte and sveltekit, and a library (roslibjs) that seems to be only usable within <head>.
It worked only in those 2 types of scenarios for me:
put everything in <head> and output to the console
import the library in <head>, but only by using <script src='https link here'></script>.
Everything else goes into onMount, outside of <head>.
1 is not acceptable, and while 2 is a temporary fix, I really don't want to rely on external links. (the site might be used in an offline environment)
What I tried
Since if I have all the code relying on the library inside <head> it works just fine, I tried to do so. But so long I couldn't find a way to export variables from <head>.
Example:
<svelte:head>
<script>
let a = 10
</script>
</svelte:head>
<p>{a}</p>
This throws an error saying 'a' is not defined.
Change the import line to <script src="node_modules/roslib/build/roslib.js"></script>, directly from the node_modules folder.
While this works in npm run dev, it doesn't once after npm run build.
What I expect
To be able to use the library with svelte3, but by using it from npm, not an external link.
One way to tackle this might be to export variables from <head>, but I couldn't find a way to do so.

HTML Filepicker without sending file itself - only filepath [duplicate]

How can I create a directory chooser in html page.
If I use input file element I can select file only, but I need to select directory instead.
I need to do this beacause the user should select a right path inside his computer.
Any solutions ?
Try this, I think it will work for you:
<input type="file" webkitdirectory directory multiple/>
You can find the demo of this at https://plus.google.com/+AddyOsmani/posts/Dk5UhZ6zfF3 ,
and if you need further information you can find it
here.
Can't be done in pure HTML/JavaScript for security reasons.
Selecting a file for upload is the best you can do, and even then you won't get its full original path in modern browsers.
You may be able to put something together using Java or Flash (e.g. using SWFUpload as a basis), but it's a lot of work and brings additional compatibility issues.
Another thought would be opening an iframe showing the user's C: drive (or whatever) but even if that's possible nowadays (could be blocked for security reasons, haven't tried in a long time) it will be impossible for your web site to communicate with the iframe (again for security reasons).
What do you need this for?
As of 2022 there is now a directory picker API:
https://developer.mozilla.org/en-US/docs/Web/API/Window/showDirectoryPicker
async function getDir() {
const dirHandle = await window.showDirectoryPicker();
// run code for dirHandle
}
In case if you are the server and the user (e.g. you are creating an app which works via browser and you need to choose a folder) then try to call JFileChooser from the server when some button is clicked in the browser
JFileChooser chooser = new JFileChooser();
chooser.setCurrentDirectory(new java.io.File("."));
chooser.setDialogTitle("select folder");
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
chooser.setAcceptAllFileFilterUsed(false);
This code snipped is from here
This is my solution. It is the same as the above answers but you should notice that webkitdirectory = "true".
<input id="design" type="file" webkitdirectory = "true" directory/>
I did a work around. I had a hidden textbox to hold the value. Then, on form_onsubmit,
I copied the path value, less the file name to the hidden folder. Then, set the fileInput box to "". That way, no file is uploaded.
I don't recall the event of the fileUpload control. Maybe onchange. It's been a while. If there's a value, I parse off the file name and put the folder back to the box. Of, course you'd validate that the file as a valid file.
This would give you the clients workstation folder.
However, if you want to reflect server paths, that requires a whole different coding approach.
This isn't provided by HTML because of the security risk. <input type='file' /> is closest, but not what you are looking for.
If you're still using IE11 on Windows 10, you may try this example that uses an ActiveX control to achieve what you want.
Again if the OS is Windows, you can use VB scripts to access the core control files to browse for a folder.
If you do not have too many folders then I suggest you use if statements to choose an upload folder depending on the user input details.
E.g.
String user= request.getParameter("username");
if (user=="Alfred"){
//Path A;
}
if (user=="other"){
//Path B;
}

dynamically rendering plain .html page on webmatrix

I'm trying to render a .html webpage using #Renderpage() method in Webmatrix but the .html extension is not supported by the method. I guess the method only supports cshtml extensions. Is there a way I can render html pages dynamically on my site (Webmatrix). I dont want to use an iframe because I'll definitely have issues with my jquery files.
I attempted something i feel is safe yet feels unsafe. I resolved to read the html file and inject it to the DOM manually using:
Array html = null;
var mypage = Server.MapPath(page);
if(File.Exists(mypage)){
html = File.ReadAllLines(mypage);
}
After reading the file.....i injected it to the DOM
<div class="s_content s fontfix left s_content2 downdown">
#foreach (var data in html) {
<text>#Html.Raw(data)</text>
}
</div>
All this runs on compilation time before the page is created for rendering.....I attempted some security measures by attempting to inject server-side C# code in the HTML file but was useless. Makes me feel safe atleast. Is this risky? What is the possible threat to this alternative. i wish i can still have an alternative proper solution from the house. Thanks though.
Assuming #Renderpage() doesn't support HTML files, why don't you try Jquery.load or Ajax. There are lots of tutorials based on dynamic loading of html content.
I do something similar but I don't use #Renderpage or an html file. Instead I am using the "onclick" event and a javascript function which opens a cshtml file. You just put this and the java script function in your main cshtml file in the hmtl section. It will open a file in the current directory called my_window.cshtml when clicked
<a onclick=openWin("my_window",700,850);>Open when clicked</a>
<script type="text/javascript">
function openWin(url, width, height)
{
myWindow=window.open(url,'_blank','width='+width+',height='+height);
myWindow.focus();
}
Hope this helps!

Getting value from <file> gives C:\fakepath\filename, even in Linux

I'm getting some very strange behaviour from a file input element in both Chrome and Opera (possibly more, haven't tested).
I have the following HTML:
<div id="profileImgContainer" class="formFile">
<label>Profile Picture</label><div>
<input type="text" id="profileImgText"><input type="button" value="Choose File" id="profileImgButton">
</div>
<input type="file" id="profileImg" name="profileImg">
</div>
And the following jQuery to get the file input's value and put it in the (visible) textbox. The actual file input is hidden.
$(".formFile input[type='file']").live('change', function()
{
$(this).parents(".formFile").find("input[type='text']").val($(this).val());
});
I've made a JSFiddle for you try out. In Firefox, the text box happily takes the filename (don't care about the path) of the file element. In Chrome and Opera, however, when a file is selected the file path in the visible text box changes to C:\fakepath\[filename] where [filename] is the name of the file chosen. This path is obviously fake but what I want to know is why it's changed to it, and whether the file in the hidden upload element will still upload fine. I'm guessing it's a security feature, but I may be wrong.
This is one attempt to mitigate the security issues you get from allowing arbitrary foreign code to run in your browser: The script (which we assume could come from a malicious attacker) does not get to see (and possibly communicate back via AJAX) information about your local files.
Imagine what could happen if a script could just freely set file uploads and submit forms.
This behaviour concerning file upload controls and scripting is mandated by some sort of standard (I believe part of the DOM specification) for this very reason.
I just want to add a new answer for people facing this issue nowadays. Similar to one of the comments, it's better to use the input element itself. For example:
document.getElementById('file-input').files[0].path
This worked for me.
Similar solution for React:
const inpRef = useRef(null)
return (
<input type="file" onChange={() => {
const filePath = inpRef.current.files[0].path
// You can use more properties by looking at the files object
}} />
)

Directory Chooser in HTML page

How can I create a directory chooser in html page.
If I use input file element I can select file only, but I need to select directory instead.
I need to do this beacause the user should select a right path inside his computer.
Any solutions ?
Try this, I think it will work for you:
<input type="file" webkitdirectory directory multiple/>
You can find the demo of this at https://plus.google.com/+AddyOsmani/posts/Dk5UhZ6zfF3 ,
and if you need further information you can find it
here.
Can't be done in pure HTML/JavaScript for security reasons.
Selecting a file for upload is the best you can do, and even then you won't get its full original path in modern browsers.
You may be able to put something together using Java or Flash (e.g. using SWFUpload as a basis), but it's a lot of work and brings additional compatibility issues.
Another thought would be opening an iframe showing the user's C: drive (or whatever) but even if that's possible nowadays (could be blocked for security reasons, haven't tried in a long time) it will be impossible for your web site to communicate with the iframe (again for security reasons).
What do you need this for?
As of 2022 there is now a directory picker API:
https://developer.mozilla.org/en-US/docs/Web/API/Window/showDirectoryPicker
async function getDir() {
const dirHandle = await window.showDirectoryPicker();
// run code for dirHandle
}
In case if you are the server and the user (e.g. you are creating an app which works via browser and you need to choose a folder) then try to call JFileChooser from the server when some button is clicked in the browser
JFileChooser chooser = new JFileChooser();
chooser.setCurrentDirectory(new java.io.File("."));
chooser.setDialogTitle("select folder");
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
chooser.setAcceptAllFileFilterUsed(false);
This code snipped is from here
This is my solution. It is the same as the above answers but you should notice that webkitdirectory = "true".
<input id="design" type="file" webkitdirectory = "true" directory/>
I did a work around. I had a hidden textbox to hold the value. Then, on form_onsubmit,
I copied the path value, less the file name to the hidden folder. Then, set the fileInput box to "". That way, no file is uploaded.
I don't recall the event of the fileUpload control. Maybe onchange. It's been a while. If there's a value, I parse off the file name and put the folder back to the box. Of, course you'd validate that the file as a valid file.
This would give you the clients workstation folder.
However, if you want to reflect server paths, that requires a whole different coding approach.
This isn't provided by HTML because of the security risk. <input type='file' /> is closest, but not what you are looking for.
If you're still using IE11 on Windows 10, you may try this example that uses an ActiveX control to achieve what you want.
Again if the OS is Windows, you can use VB scripts to access the core control files to browse for a folder.
If you do not have too many folders then I suggest you use if statements to choose an upload folder depending on the user input details.
E.g.
String user= request.getParameter("username");
if (user=="Alfred"){
//Path A;
}
if (user=="other"){
//Path B;
}