How To Access Local File System With Chrome Extensions - javascript

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;
});
...

Related

React JS - Reading environment configurations from external property file

Problem :
I am new to React JS, and looking for an option to read environment configs from an external property file. This problem is more specific for one of my clients, who is looking to have an option to change the environment files dynamically. E.g. change the hostname/port dynamically whenever there is a change. The build process is not owned by my client. I create a minified final package, which my client deploys it on tomcat/web server.
Tried Solution :
With some read-outs, I have configured .env files for different environments and able to successfully read configs from these files. However, these are more of a build process environment files. And, I am trying to find a way to read the configs from an external source after my package is created.
Possible solutions : Here is one possible approach I can think of -
Read external property file using libraries like "properties-reader". I will provide the property file as part of my release bundle (i.e. build folder). My client can change this property file whenever required.
Please suggest if this is the correct approach or is there a better solution to this problem?
A Solution which worked for me !!
1) Create a "config.js" file inside public folder of react project. Sample Content of the
"config.js" file -
window.env = {
API_DOMAIN_ADDR: "http://localhost:8080"
};
2) Refer "config.js" file inside index.html. Code for index.html will be -
<body>
<div id="root"></div>
<script src="%PUBLIC_URL%/config.js"></script>
</body>
3) Now, content of the config.js file will be accessible to react code. Sample code to retrieve the value of config.js variables -
window.env.API_DOMAIN_ADDR
Add this code wherever variable value needs to be accessed. I added this in my service class which is making ajax call.
I would suggest using something like Firebase Realtime DB. I had a similar requirement for pointing the App builds to production or development server APIs for my company. For this, we use to load a Firebase Config and from there the UI used to pick up the host server endpoint.
Advantages:
This saves you from deploying your build folder every time.
This is realtime and less prone to errors.
FirebaseDB is free for small stuff like this.
The second option is to create two environment files which I see you have already done.

How to link javascript in html

I am creating browser based video editing tool. I want a user to first download a ~70mb javascript file and store it somewhere on his computer. I want to link that file when my website is opened. How can I achieve that.
EDIT
What i meant is that there are various files like js1.js,js2.js... all sums upto 70mb . So i will offer a zip folder to download and only link js1 or js2 file etc depending on the effects user wish to apply
i am sorry to inform you but i think there is something really wrong with what you are trying to do.
A "solution" would be to just cache the javascript on the user's browser so any subsequent requests parse the cache instead of requesting the resource again from the server.
You should know however that if you are in need to download ~70mb of a javascript file you are doing something wrong. I have a whole web app project that when published the total size is around 60mb, all files required to properly run included, and its a damn big codebase in there.
I find it very hard to believe there is ever a need for a single javascript file to be that big, in any case maybe a simple caching should do the trick
That is actually done automatically. Once you add a <script> tag with a link to a local js file (also stored on the server) the file is loaded automatically.
See HTML <script> src Attribute for more information on that.
You can only reference to js files on the server. Files on the server could look like this:
index.html
somefancyjsfile.js
You can then reference from inside your html file to the js file via the <script> tag.
I'm not sure though if the size is not a bit too much...

cannot find js file

I have stucture code like this:
I try to load javascript into php file like this:
But i have an error like this:
This is my html :
And this is another javascript:
And i try to copy paste the link, and i got an error 404 not found. How can i fix it? Thanks.
Permissions
When the host is correct, and the file is in the right place, and you have no other networking problems, you may sometimes still get a 404 because of bad file permissions. If a server does not have permission to access a file, it may send out a 404 error in response. The reason why some "Not Authorized" error is not given instead, is that this would reveal more information about the files than you, the owner of the server, may intend. The way to respond to requests for privileged files without revealing whether or not they exist is to give a 404.
On Windows, you can view and change the permissions from the File Explorer by right-clicking on the file or folder, then going to Properties -> Security -> Edit. For more information, see the notes on permissions on Microsoft's site.
File Types
Besides permissions, a server must also be configured to serve the type of file you are accessing. If files with different extensions are served, but .js files are not, check the configuration of your server to make sure that .js files aren't blacklisted (or not whitelisted, as the case may be).
Directory Location
You should also verify that the files are actually stored in the top-most directory of the web server if that's how you are accessing them. If they aren't, you may need to prefix the path with the path from the webserver root to your application directory. E.g., instead of fusioncharts/..., you may need /path/to/fusioncharts/... or ../../path/to/fusioncharts.
Other Considerations
In your particular case, you should also verify that the files inside the fusioncharts folder are actually structured the way you think. (E.g., is there really a js/[insert name here].js file inside the fusioncharts folder?
If none of that solves your problem, try to take something that is working and gradually make it more and more similar to the files that aren't working. By figuring out at which point you go from a working setup to a not working setup, you may discover the problem.
If you are referring to a file with path: /ui/new-file.js
then,
1.In html file include
<script type="text/javascript" src="/ui/new-file.js"></script>
2.In server.js or app.js whichever you have, include
app.get('/ui/new-file.js', function (req, res) {
res.sendFile(path.join(__dirname, 'ui', 'login-file.js'));
});
Assuming you are using codeigniter, you can use base_url() function to include JS files in your codeignitor view template file.
<script src="<?php echo base_url(); ?>fusioncharts/js/fusioncharts.js" type="text/javascript"></script>
codeigniter default view template is called welcome_message.php and this file is located in application/view folder.
This is how I include js files in my codeigniter projects. Hope this will help.
In the html you can write *script** in the head or in the body, but not in your file js, delete this in fusionCharts.js
<script type=text/javascript>
In fusionCharts.js write only the function without the script
If you are developing locally, try clearing your cache.
Google Chrome likes to use the cached JavaScript files instead of the real ones.
Clearing your cache should resolve the issue.

Restart Apache Tomcat to serve changed Javascript files?

I was under the impression that if I deployed my application (using Ant) then JS files, along with HTML, CSS and images, would be automatically served by Tomcat.
However, after editing Javascript files I have to restart Tomcat in order for the changes to be updated.
My JS files are in a 'js' directory off of root (not in WEB-INF).
I am using FF3.6.
Any help?
I 've never worked with Tomcat but I find it hard to imagine it wouldn't serve changed JS files straight awayafter deployment. My guess is this is a caching issue on the browser's side. Can you try to force a refresh by opening the actual CSS file and pressing F5?
The usual approach to making sure a JS file gets updated is embedding it with a GET parameter that marks the version/revision:
<script type="text/javascript" src="/js/script.js?version=51"></script>
when you update the script's revision, and change the GET parameter, the browser should forget the cached version and re-load the file.
According to http://tomcat.apache.org/tomcat-5.5-doc/config/context.html
cachingAllowed -
If the value of this flag is true, the cache for static resources will be used. If not specified, the default value of the flag is true.
I found out that Tomcat reload files from the /temp directory which was set by setting antiresourcelocking to true in the context xml's. Thanks guys.

Drupal Filefield won't upload javascript files?

I've got a site where individual pages might require some javascript or CSS files hooked into their heads. I'm trying to keep everything client side when it comes to managing this process, rather than getting on the FTP and sorting everything out in the code so I need to be able to upload css and js files.
I've got CCK filefield up and running, and it works with css files, but it refuses to upload .js files. It instead seems to view every .js as ".js.txt" and then the file appears on the server as thisismyfile.js.txt
Not ideal...
Does anyone know how to work around this. Is it a mime type problem with Drupal or the server, or is Drupal set up to avoid script uploads and n00b hack attacks.
Once the files are uploaded I intend to use PHP mode on the page or node to call drupal_add_css and drupal_add_js.
Looking at the field_file_save_file() function in field_file.inc from filefield module, you can find the following snippet
// Rename potentially executable files, to help prevent exploits.
if (preg_match('/\.(php|pl|py|cgi|asp|js)$/i', $file->filename) && (substr($file->filename, -4) != '.txt')) {
$file->filemime = 'text/plain';
$file->filepath .= '.txt';
$file->filename .= '.txt';
}
So yes, it's a 'security thing', as Jeremy guessed.
You could patch that RegEx for an immediate 'fix', but that would remove this otherwise useful security check completely for all filefields used on the site.
So a more specific workaround might be a better approach. Since you want to add the files via drupal_add_js() calls from code anyways, you might as well do the renaming there, adding some kind of verification to make sure you can 'trust' the file (e.g. who uploaded it, whatever).
Edit: Concerning options to rename (and alternatives) when calling drupal_add_js():
For renaming the file, look into the file_move() function. A problem with this would be that it won't update the corresponding entry in the files table, so you would have to do that also, if the move operation succeeded. (The filefield just stores the 'fid' of the corresponding entry in the files table, so you'd need to find it there by 'fid' and change the 'filename', 'filepath' and 'filemime' entries according to your rename/move)
Alternatively, you could just load the content of the *.js.txt file and add that string with the 'inline' option of drupal_add_js(). This would be less 'elegant' and could be a performance hit, but if those are not important criteria in your specific case, it is less trouble.
Yet another option would be just passing the *.js.txt file as is to drupal_add_js(), ignoring the 'wrong' extension. A short local test showed that this works (at least in firefox). This might be the 'least effort' solution, but would need some additional testing concerning different browser behavior concerning usage of 'misnamed' js files.
Allowing Drupal to upload javascript files would be a security risk, which is also why it doesn't allow you to do it, but instead appends the .txt extension. The reason is that js files are executable along with php, pl, py, cgi, asp. So if Drupal could upload those files to the server, it would be possible for evil doers to upload a file and run it doing all kinds of nasty things on your server, basically anything is possible. Best thing would be to find a different way of uploading files which are secure.
I had a similar need, and found a way to get around the security by first changing the 'allow_insecure_uploads' variable value by running this line of code in your hook_install:
variable_set('allow_insecure_uploads', 1);
Then in a module add this function
/**
* Implementation of FileField's hook_file_insert().
*/
function MODULE_NAME_file_insert(&$file) {
//look for files with the extenstion .js.txt and rename them to just .js
if(substr($file->filename, -7) == '.js.txt'){
$file_path = $file->filepath;
$new_file_path = substr($file_path, 0, strlen($file_path)-4);
file_move($file_path, $new_file_path);
$file->filepath = $file_path;
$file->filename = substr($file->filename, 0, strlen($file->filename)-4);
$file->filemime = file_get_mimetype($file->filename);
$file->destination = $file->filepath;
$file->status = FILE_STATUS_TEMPORARY;
drupal_write_record('files', $file);
}
What this does is in the hook_insert call it checks if a file has the extension ".js.txt". If it does it copies it to a new location and renames it. This is after the security check so its ok. I don't think you need to worry about the cache clear deleting your js files as long as you don't put them in the files/js directory. Create your own directory for you module and you should be ok.
I faced this situation when I wanted to allow .js file to be upload as is (without .txt and with 'application/javascript' mimetype) for a specific field. Also, I didn't wanted to alter Drupal core... of course.
So I needed to create a module implementing hook_file_presave(). This also work for Multiupload File Widget, since its hook is on file_save().
Note that you would have to replace MYMODULE_NAME and MYFIELD_NAME by your own values.
function MYMODULE_NAME_file_presave($file) {
// Bypass secure file extension for .js for field_additional_js field only
if((isset($file->source) && strpos($file->source, "MYFIELD_NAME") !== FALSE) && substr($file->filename, strlen($file->filename) - 7) == ".js.txt") {
// Define new uri and save previous
$original_uri = $file->uri;
$new_uri = substr($file->destination, null, -4);
// Alter file object
$file->filemime = 'application/javascript';
$file->filename = substr($file->filename, null, -4);
$file->destination = file_destination($new_uri, FILE_EXISTS_RENAME);
$file->uri = $file->destination;
// Move fil (to remove .txt)
file_unmanaged_move($original_uri, $file->destination);
// Display message that says that
drupal_set_message(t('Security bypassed for .js for this specific field (%f).', array('%f' => $file->filename)));
}
}
Drupal also "munges" javascript files. To prevent Drupal from automatically adding underscores to the filename there is a hidden variable that is checked before the filename is "munged".
Setting the variable to 1 solves the issue for me (along with altering the REGEX in includes/file.inc).
I hate hacking core, but this seems like a poor design to me. Javascript files are not server side scripts like php, py, pl, cgi, and asp.
You can use the allowed file extensions settings to prevent php and other server side scripts from being uploaded.
eg:
variable_set('allow_insecure_uploads', 1);
See:
http://api.drupal.org/api/function/file_munge_filename/6
So uploading .js files to the files directory is pretty much impossible.
Even if you manage to get .js files uploaded cleanly, these files will get deleted when the cache is cleared.
Any js files that live inside the files directory will be deleted whenever the drupal_clear_js_cache() function is executed.
http://api.drupal.org/api/function/drupal_clear_js_cache/6
So Drupal sees .js files living in the file uploads directory as temporary.
Now I understand why they are appending ".txt", it is to prevent them from being removed when the cache is cleared.
So as a compromise I guess I will just be uploading .js files manually (via FTP) to the /misc folder. :(

Categories

Resources