accessing document.getElementById from another window - javascript

I have two .html files (Intro.html and Main.html) sharing an external .js file.
My first .html file opens up the 2nd .html via a customized button and .online event from the external .js file using
document.getElementById("leaveButton").onclick = function () {
location = "Main.html";
}
My second .html file also has several buttons on its own page/window also being accessed by document.getElementById.onclick from the external .js file.
There are no problems and everything works fine if I keep separate .js files for each .html file.
However, when I have them share the same .js file, each .html page in the console complains about the other's document.getElementById("idName").onclick items. This is the error message I get,
Uncaught TypeError: Cannot set property 'onclick' of null
How do I resolve this using pure Javascript?

The simplest solution would be to only attempt to add the onclick() handler if the element exists. Something like:
if (!!document.getElementById("leaveButton")) {
document.getElementById("leaveButton").onclick = function () {
location = "Main.html";
}
}

Related

jQuery - Image path replace folder error

I have client specific images in many .html pages and I want to redirect the images path to other folder from default folder.
I am trying to achieve the same by following code from external
javascript file which is working as expected. But getting an error and HTML source still showing as old file path
I am getting an error as below though Images are loading
GET file:///E:/User/Images/test.png net::ERR_FILE_NOT_FOUND
PS: I am doing this scr
$(document).ready(function () {
$(function () {
var img = $("img");
img.each(function () {
var src = $(this).attr('src');
if (src.indexOf('Images/') > -1) { // Default path of the images
$(this).attr('src', src.replace("Images", "Images/client")); // New path
}
});
});
});
And also, if I check source code, still it is showing as Images/test.png instead of Images/client/test.png
It should be ,
$(this).attr('src', src.replace("Images", "Images/client"));
First, you have to use a web server instead of what you are doing,
GET file:///E:/User/Images/test.png net::ERR_FILE_NOT_FOUND
means you are open the file locally.
However, your code is correct and doesn't have any error, you are trying to replace the word (client) with (Images/client) and because your src doesn't contain any word (client), the replace is not taking a place, your correct code should be something like:
$(this).attr('src', src.replace("Images", "Images/client"));
This will work for sure, test and let us know if it worked.
Thanks.

Mustache.js - using partial inside an external template file

I'm using external template file and I want to use a partial inside the template file (.mst file inside another .mst file)
For example I have template.mst file with this code:
{{#comments}}
// Here I want to use another external .mst file
{{/comments}}
So I careated a comment.mst file beside the template.mst file and now I'm trying to use {{>comment}} to call this external template file - full example:
{{#comments}}
{{>comment}}
{{/comments}}
But it doesn't work. I tried to play with it a little bit, I tried to add the file extension {{>comment.mst}} and I tried to add the path {{>temmplates/comment}} and any pther option.
This is the code I use to load the template:
$.get('templates/template.mst', function(template) {
var rendered = Mustache.render(template, postData);
$('.inner-container').prepend(rendered);
});
I guess I missing something, Can someone give me an hint? Thanks!

Access fileEntry after dropping a file in a Chrome App

Is it possible to get a fileEntry object in Chrome Apps by opening a file via Drag'n'Drop? When I drop a file into my app I only get a file object which seems to be unrelated to the file system. I can't use that object to save the file after changing it.
I get the file like this:
document.body.addEventListener('drop', function (event) {
file = event.dataTransfer.files[0]
});
What I want to do
I'm developing a text editor and I want to add a feature to open a file by dragging it into my app.
As I said: I already get the content of the file, but I can't write changes back to the file since I need a fileEntry object in order to do so.
Okay, I just found it while inspecting the event object. In the event object there's a function called webkitGetAsEntry() to get the fileEntry object. Here's the correct code:
document.body.addEventListener('drop', function (event) {
fileEntry = event.dataTransfer.items[0].webkitGetAsEntry();
});
This is the object you can use to write changes back to the file system.
Code for reference:
// Of course this needs the "fileSystem" permission.
// Dropped files from the file system aren't writable by default.
// So we need to make it writable first.
chrome.fileSystem.getWritableEntry(fileEntry, function (writableEntry) {
writableEntry.createWriter(function (writer) {
// Here use `writer.write(blob)` to write changes to the file system.
// Very important detail when you write files:
// https://developer.chrome.com/apps/app_codelab_filesystem
// look for the part that reads `if (!truncated)`
// This also is very hard to find and causes an annoying error
// when you don't know how to correctly truncate files
// while writing content to the files...
});
});

Javascript dynamically show local file

I have a local text file which is kept changing by other programs. I want to write a html and javascript based web page to show the content of file dynamically. I have searched in google and found that most solutions require to get this text file via html element. I wonder if there is a way to get the file via a fixed path(lets say it is a string of the file directory) in javascript. I am using Javascript fileReader. Any help will be appreciated.
This is not possible using javascript running inside the browser. You will not be able to do anything outside the browser.
EDIT:
You could run a Node.js server though that runs on localhost and does your file operations you desire. You could build a API so your html page that you load in the browser calls your serverscript to do your file operations.
Do you understand what I mean?
How much information does the text file hold, Depending on your scenario it might be worth looking into javascript localstorage W3SCHOOLS local storage. Would that help your situation ?
What you can do is allow the user to choose the file of interest, using a file-input. Once done, the browser wil have access to the file, even though the JS wont have access to the file's full-path.
Once the user has chosen the file, you can reload it and refresh the view pretty-much as often as you please.
Here's a short demo, using a file input (<input type='file'/>) and an iframe. You can pick pretty much anything the browser will normally display, though there are limits on the size of the file that will work - due to the limit of the length of a URL - the file's data is turned into a data-url and that url is set as the source of the iframe.
As a demo, pick a file and then load it. Now, open the file in another program and change it. Finally, press the load button once again - the new content now fills the iframe. You can trigger the loading of the file by a timer or any other event in the page. As far as I'm aware, you cannot re-load it when it changes, since there's no notification from the OS - you have to use a button, timer, element event or whatever. Basically, you have to poll for changes.
<!DOCTYPE html>
<html>
<head>
<script>
function byId(e){return document.getElementById(e);}
window.addEventListener('load', onDocLoaded, false);
function onDocLoaded()
{
// uncomment this line for on-demand loading.
byId('loadBtn').addEventListener('click', onLoadBtnClick, false);
}
// fileVar is an object as returned by <input type='file'>
// tgtElem is an <iframe> or <img> element - can be on/off screen (doesn't need to be added to the DOM)
function loadFromFile(fileVar, tgtElem)
{
var fileReader = new FileReader();
fileReader.onload = onFileLoaded;
fileReader.readAsBinaryString(fileVar);
function onFileLoaded(fileLoadedEvent)
{
var result,data;
data = fileLoadedEvent.target.result;
result = "data:";
result += fileVar.type;
result += ";base64,";
result += btoa(data);
tgtElem.src = result;
}
}
function onLoadBtnClick(evt)
{
var fileInput = byId('mFileInput');
if (fileInput.files.length != 0)
{
var tgtElem = byId('tgt');
var curFile = fileInput.files[0];
loadFromFile(curFile, tgtElem);
}
}
</script>
<style>
</style>
</head>
<body>
<button id='loadBtn'>Load</button><input id='mFileInput' type='file'/><br>
<iframe id='tgt'></iframe>
</body>
</html>
you can use nodejs to watch for a filechange using watchfile module, if you just want to watch the filechange and its content. you can run following code using node, but it only consoles the file changed in your terminal.
var fs=require('fs');
fs.watchFile('message.text', function (curr, prev) { //listens to file change
fs.readFile('message.text', function(err,data){ //reads the file
console.log(data.toString()); //consoles the file content
});
});

Javascript read text file from current directory

How to read text file (text1.txt) from current directory using javascript without jquery. I tried the following code.
var file = "text1.txt";
var reader = new FileReader();
var result = reader.readAsText(file);
console.log(result);
The FileReader API is usually used to read files selected via the an <input type="file">. It cannot read arbitrary files. The readAsText method expects to receive with a Blob or a File object, not a string containing a file name.
To read files that are siblings of the HTML document, use XMLHttpRequest. This will reliably work if you load the document over HTTP(S). If you are using a local HTML document (via a file: URI) then security restrictions in many browsers will prevent it from working (and you should run a local web server instead).
Option A, Your use-case prevents you from using an http or php server.
You can include local content in your javascript as a variable using a script include. If you are opening the page locally, as a file from a directory, this is the only way to include local content in the web page.
To include local content, put this above your other script tag:
<script src="text1.txt"></script>
and edit your text1.txt file so it assigns all the content to a variable:
gbl_text=`...contents of my text file...
...more contents...
...and so on....
`
You can use a script to create this include file, for example (use the ` tick mark below the tilde ~ key):
echo -n "var gbl_text=\`" > text1.txt
cat your-original-file.txt >> text1.txt
echo "\`" >> text1.txt
Then use the gbl_text variable in your javascript as needed...
function dosomething()
{
if (typeof(gbl_text)=='undefined'){
setTimeout('dosomething()',500) //call back until defined
}else{
console.log(gbl_text)
}
}
Option B, Your use-case would allow you to use the php-cli built-in server.
If you are able to run php-cli, you can open the page on the built-in php webserver, and read and write local content with a php call. To install and use php on linux,
sudo apt install php7.0-cli
#To use the php built-in webserver, run:
php -S localhost:8000 -t /path/to/your/content
So, instead of opening your html as a file, you would open as an http web page:
firefox http://localhost:8000/mypage.html
#or browser of choice
Now the local webpage is being served by an actual (local) http server with php support, and you can manipulate local files with it.
Here is simple example showing how to read and write to a local file using jQuery and php. Download and include jQuery (see jQuery.com) in your html file.
Contents of dofile.php:
<?php
$dowhat = $_REQUEST['dowhat'];
if ($dowhat=='save'){
$myvar = $_REQUEST['myvar'];
file_put_contents('myfile', $myvar);
}elseif($dowhat=='read'){
$myvar=file_get_contents('myfile');
echo $myvar;
}
?>
Contents of mypage.html:
<script src='jquery-3.2.1.js';></script>
<!--make sure the filename matches the jQuery you use-->
<script>
function savevar(){
var myvar=document.getElementById('mytxt').value
var path="dofile.php?dowhat=save&myvar="+myvar
$.get(path, function(data){
console.log("saved ...\n"+myvar)
alert("saved ...\n"+myvar)
});
}
function clearbox(){
document.getElementById('mytxt').value='reading file...'
setTimeout('getvar()',1000)
}
function getvar(){
var path="dofile.php?dowhat=read"
$.get(path, function(data){
console.log(data);
document.getElementById('mytxt').value=data
/*do other things with data here*/;
});
}
</script>
<html>
Type something in the text box.<br>
Use the Read and Write buttons to verify <br>
text is saved and read back.<br>
<input id='mytxt' value='type text here' onclick=document.getElementById('mytxt').value=''><br>
<input type='button' value='Save' onclick=savevar() ><input type='button' value='Read' onclick=clearbox() >
</html>
Please distinguish 2 kinds of reading files:
reading "from internet" - use XMLHttpRequest to read any kind of file
reading "from client" - use FileReader or <input type="file">
make a tiny iframe.
load the file there.
read it with iframe.innerHTML

Categories