https://codesandbox.io/s/optimistic-sammet-1yms2?file=/public/index.html
This is my minimal reproducible example.
When the page was only static html with javascript the sounds were working. After refactoring into a React app the sounds have stopped working and I get 2 errors: Uncaught Error: The error you provided does not contain a stack trace. and (index):1 Uncaught (in promise) DOMException: Failed to load because no supported source was found.
When I paste the HTML file path into the browser the sounds are working, but when I run the app on localhost there are errors and no sounds. The rest of the javascript is working, and I have made sure the file path for the sounds is correct.
This is my directory layout.
This code is from daily-planner/public/planner.js and shows the audio play functions:
var penNoises = ["../src/sounds/Pen1.wav", "../src/sounds/Pen2.wav"];
var randomPen = Math.floor(Math.random() * penNoises.length);
function penSound() {
var audio = new Audio(
penNoises[Math.floor(Math.random() * penNoises.length)]
);
audio.volume = 0.1;
audio.play();
}
function penCross() {
var audio = new Audio("../src/sounds/penCross1.wav");
audio.play();
}
The event listeners that call these functions are attached to <li>'s that are dynamically generated from an array, not <audio> elements.
The reason why this doesn't work is the way React compiles the files.
All that is on the src folder, is packed up in a folder named 'static'.
And every file in there is properly linked to the index.html file.
(and I mean, linked as we would expect from the un-compiled project).
It is recommended to load assets on src.
But links on the public folder remain intact, they do not follow the re-arrangment in directories done by the compilation. Run npm run build or npm start to check out.
So the path on your planner.js contains a URL - that's expected - but is pointing nowhere.
That being said/sad, what is logic in the raw project, may not be what is compiled. To be better off maybe look at these rules.
Basically, planner and .wav would be better placed in the source folder. You can also move the .wav file in the public folder (not best option).
I've fixed your codesandbox with that second approach. In part, because it's not easy to deduce from the post if you really need that planner.js in public or not.
Anyways, Hope this helps.
You can just put the audio file inside of the public folder since the script using it is inside public.
function playSound() {
var audio = new Audio("./penCross1.wav");
audio.play();
}
Alternatively, you can put planner.js inside src so you can access the wav file residing inside src
Related
I am trying to build a Chrome extension but I have encountered a problem. I need access to a file that is in the same directory as my JS script. Here is the representation:
my_script.js
My Folder
|-> my_file.file
I use a third party library that does some required things with it. And I need to pass in the path to my_file.file The problem is my_script.js gets injected into the website I am trying to change and the code instead of searching on the local file system it tries to find it in www.website.com/My Folder/my_file.file which obviously does not exist. How can I make it so that it seacrhes relative to my_script.js? I unfortunately can't pass the file itself to func(), it has to be the path of the file. The file I am trying to reach is about 200MB which I was planning on shipping with my extension. Also this project is vanilla JS. Thank you!
my_script.js
...
lib.func('My Folder/my_file.file').then(function (out) {
document.out = out;
});
...
I'm having some trouble getting images to work after my app is deployed to AWS Amplify. I created a pretty simple app that consists of just HTML, CSS and JS files (no angular/react/flutter etc.). My folder structure is currently:
- .html files
- styles.css
--- scripts
|___app.js
|___config.js
|___aws.js
--- images
|___image1.PNG
|___image2.PNG
|___image3.PNG
|___image4.PNG
In my app.js file, I've got a few dynamic image creations setup in the same way (just different variable names and image files):
var image = document.createElement('img');
image.src = '../images/image1.png';
image.addEventListener('click', myFunction);
image.style.cursor = 'pointer';
Specifically the image.src line; I've tried different combinations such as:
image.src = '../images/image1.png';
image.src = './images/image1.png';
(one suggestion I found said to remove one of the periods (not sure why))
image.src = '/images/image1.png';
(placing the images folder inside the scripts folder)
image.src = 'image1.png';
(placing the actual images at the same level as the scripts)
I've even tried placing the images in an S3 bucket, and then using #3 add an image rewrite as described here: AWS Rewrite/Redirect Documentation.
No matter what I try, after pushing my code to GitHub and then after my AWS Amplify app finishes building the code, when I go to website, all the images are showing as if they couldn't be found and the dev console always shows something along the lines of Image could not be found. The server returned with: 404 Could not be found error.
The code works perfectly fine and the images show up on my local machine when I open the Live Preview using either Brackets.io or VS Code, just not when deployed to Amplify.
I've also tried setting up in the Amplify console the Rewrites and Redirects as it mentions in this Github forum: Github Forum but to no avail. My current Rewrites and Redirects section of the Amplify console effectively look like what's shown in the first link.
I've got to be missing some kind of setup to get this working but I'm not sure what it is. Hopefully it's a simple fix and I don't need to effectively re-do the project some other way.
Thank you in advance for any assistance.
I figured it out. I decided to try and use GitHub Pages instead to see if the same problem occurs there and it does. I did some research on why it wouldn't show up there and I found this article: GitHub Pages Stackoverflow which basically says that the filename, extension and folders are all case sensitive. I didn't think that AWS Amplify would have this problem but it does.
My files had .PNG as the file extension but in the code I used .png. After changing it in the code and re-deploying, it worked.
I'm trying to load a bunch of png images that are in a folder in my project. I'm using a function that takes in an array of strings that signify the name of the actual images.
The actual html that comes up in the console seems correct, however the images don't get loaded. The weird thing is, if I hard code in the html with the src of one of the images, the src in the inspector comes up as 'name.93439.png' with random numbers in between the name and the file extension, and the image shows up. But the source I am injecting in the javascript using template strings is no different than what I am putting into the html when I hard code it.
So is there something I'm missing here with loading images? Why does hard coding it in work, but when I try using JS it doesn't give the same results? Code below:
FILE STRUCTURE:
index.html
/src
index.js
/assets
/images
...{all of the images}.png
function loadImages(names) {
names.forEach((name) => {
let image = document.createElement('img');
image.src = `src/assets/images/${name}.png`;
let newDiv = document.createElement('div');
newDiv.appendChild(image);
document.getElementById('images').appendChild(newDiv);
});
}
This happens because parcel hashes your assets during building. When executing the js, ${name} is not aware of the (parcel) hash and therefore doesn't finds the correct file. Try to take out the assets from the build process and copy them to your dist folder (you'll probably want to automate this at some point). So the assets file names do not get hashed.
I'm having a hard time linking an external script to a single file component in Vue. My application is structured like this:
So the file I want to link to is components/Sshy and the destination file (I believe) would be ../javascripts/
This isn't my first time doing that, and I have other scripts connected that I have successfully referenced in other single file components as either:
../javascripts/<name>
#/javascripts/<name> (Src is aliased)
Like so:
I'm trying to do the equivalent on a compiled file that isn't well suited to being exported as a module and imported like that. The suggestion I found on a way I could attach this script to a single file component is here.
I tried to copy this method like this:
mounted () {
let testScript = document.createElement('script');
testScript.async = true;
testScript.type = "text/javascript";
testScript.setAttribute('src','../javascripts/test.js');
document.head.appendChild(testScript);
},
But keep getting an error that seems to indicate it isn't picking up the file right. The error found is
uncaught syntax error: Unexpected token <
And devtools reports it like it is occurring in the index.html where my vue files get injected. In searches, it looked like the real cause may be the file not being connected properly (Here)
I haven't managed to identify what the issue is still though.
An invalid src path (i.e., ../javascripts/test.js) is likely the problem. Your server is probably configured with an index.html fallback, which is returned for files not found. You can confirm this in your browser's developer tools (find test.js in Network Panel). Since the HTML file (which probably begins with <head>) is sourced into the <script>, you get a JavaScript syntax error for the < character of <head>.
You'll need to update the src path to be relative to the root document and not to the directory of the component.
I have a spring based web application MyWebapp built using maven and deployed on Websphere 6.1
The folder structure is:
MyApp --> src ---> main --->
The main folder is further having resources and webapp folders.
webapp folders is having other folders like images, theme, jscript, JSP, META-INF, WEB-INF
images folder is having icons folder with say example.png
So fetching example.png on localhost as:
http://localhost:9080/MyWebapp/images/icons/example.png
succeeds.
In jscript folder I have a sample.js javascript file where some functions are defined.
I am importing this javascript file in JSP pages as:
<script src="<%=request.getContextPath()%>/jscript/sample.js" type="text/javascript" language="Javascript"></script>
This javascript file is having a function which tries to fetch image as below:
iconFile = '../images/icons/search_result.png';
anchor.style.backgroundImage = 'url(' + iconFile + ')';
anchor.style.backgroundRepeat = 'no-repeat';
anchor.style.backgroundPosition = '1px 2px';
anchor.className = 'toplevel-tab';
The complete function basically tries to place a icon before some text in JSP.
The code gets parsed. However, the image does not get displayed.
Running the code independently on a simple html with the png images in the same folder as html and javascript files succeeds. Here i will just have iconFile = "search_result.png"
So, it is not code issue.
Issue is that the image is not getting located or the server is unable to find the image in above javascript code.
What am I doing wrong ?
How can I solve it ?
The answer for https://stackoverflow.com/a/8298652/887235 which I accepted earlier does not work.
So please do not downvote this question as a duplicate one.
Also I am working on restricted environment where access to programs like Tail will not work.
Changing
iconFile = '../images/icons/search_result.png';
to
iconFile = '/images/icons/search_result.png';
also does not work!!
Thanks for reading!
You just have to understand how relative paths work. Even if the path is in a JavaScript file, the path is not relative to the location of this JS file, but it's relative to the URL of the HTML page being displayed in the browser.
So, if the URL of the page executing this javascript code is
http://foo.bar.com/myWebApp/zim/boom/tchak.html
and the URL of the image is
../images/icons/search_result.png
The absolute URL of the image will be
http://foo.bar.com/myWebApp/zim/boom/../images/icons/search_result.png
which is the same as
http://foo.bar.com/myWebApp/zim/images/icons/search_result.png
An absolute path like /images/icons/search_result.png is also resolved from the root of the web server, and not the root of the webapp (the browser doesn't know what a Java webapp is and doesn't care). So it's resolved as
http://foo.bar.com/images/icons/search_result.png
You would need to prepend the context path to the path to make it really absolute:
<%=request.getContextPath()%>/images/icons/search_result.png
or, without scriptlets:
${pageContext.request.contextPath}/images/icons/search_result.png
You need to give your javascript an awareness of the path to the root of your application, as this will change on context. Start by declaring a global variable, such as:
<script>
var siteroot = "<%=request.getContextPath()%>";
</script>
Then, you are ready to use it later, such as:
iconFile = siteroot + '/images/icons/search_result.png';