How to include Javascript files into shopware5 theme - javascript

I am unable to add javascript files to my first Shopware5 theme. I tried the following method given in one of online articles.
https://developers.shopware.com/designers-guide/theme-startup-guide/
I added my js files into the array on Theme.php file and upload javascript files to the ‘frontend/_public/src/js’
/** #var array Defines the files which should be compiled by the
javascript compressor */
protected $javascript = array(
'src/js/jquery.my-plugin.js'
);
However the above array was not avilable on my Theme.php file but I added my js files into the array and tried loading it on my theme. I cleared all my caches when I checked the site.

You have to clear all caches and also do a re-compile of the theme. Have in mind that you have to place the js into frontend/_public.
The full path of your js-files should be themes/YourTheme/frontend/_public/src/js/jquery.my-plugin.js.

Related

Only js file per page in laravel

In a Laravel setup using Laravel mix, the mix.js(['resources/js/app.js','resources/js/new-offer.js'], 'public/js') puts everything in one file, app.js.
What I am trying to achieve is to have multiple .js files each for one page. For example. I want to have index.js for my index.blade.php and new-offer.js for my new-offer.blade.php etc ...
The idea is that each page is server side rendered and each page represents a static page comming fromm the server and each one should has it's own set of js files that works in. How this should be done, is it recommended, what are other arhcitectures ?
You can use multiple concatenated .js(...) statements. In your case:
mix.js('resources/js/app.js','public/js').js('resources/js/new-offer.js' ,'public/js')
This will createapp.js and new-offer.js files in your public js folder

How to get the compressed file name in Drupal?

After compressing the JS file in Drupal I got a randomly JS file name.
My question how I can get this file name to add it to my javascript?
Drupal code: import and compress
<?php drupal_add_js(drupal_get_path('theme', 'mytheme') . 'mybigfile.js'); ?>
Random file name Result:
js_2KQpJNjjupC1Beoweoqpok2JCXhe0sJ6YBllaRDUXYQ.js
Trying to Call the mybigfile.js file:
<script>
telInput.intlTelInput({
validationScript: "mybigfile.js"
});
</script>
As far as I know, you can not get the name of the concatenated JavaScript file generated by Drupal using PHP.
Your best option would be to avoid your JavaScript file mybigfile.js from being concatenated and compressed. Then you can apply your validation script by calling the file name.
You will have to set the preprocess property to false inside drupal_add_js $options array, to prevent the file from being aggregated.
drupal_add_js(drupal_get_path('theme', 'mytheme') . '/mybigfile.js', array(
'type' => 'file',
'preprocess'=> false,
));
Update
If you want to compress a single JavaScript file, you have the option to use AdvAgg API.
Unfortunately, I can't find any documentation for how to do that. But you start with the following:
download and install advagg and enable the submodule advagg_js_compress.
inside the advagg_js_compress submodule folder, find the file advagg_js_compress.advagg.inc and open in your text editor. Here you can find a few helper functions that will help you compressing your JavaScript file.

Wordpress child theme enqueue custom javascript

I'm having some trouble using a custom javascript file in my WP child theme.
What I've done in order to try and only make changes to the child theme is create a functions.php in my child theme's root folder. Like that I believe this functions.php to be prepended to the actual theme's fucntions.php file.
Now in this functions.php I want to enqueue my custom javascript file and thats where I get stuck. I'm having some difficulties thoroughly understanding the enqueue function but I have basically grabbed the enqueue function used in the original functions.php and I've altered it so it would point towards my child theme's "js" folder and then to the custom.js file in there.
Here is what my child functions.php looks like:
<?php
define( 'CHILD_DIR', get_stylesheet_directory() );
wp_enqueue_script('responsive-scripts', CHILD_DIR. '/js/custom.js');
?>
It looks like it is properly linking, or at least pointing to the correct file when I check my chrome console but it does say that it's not found (404) When I check the network tab in chrome it says the custom.js file's type is text/html (not application/javascript, which is what I see for my other javascript files), also for Time it says "pending".
Could anyone help me see where I'm going wrong?
The function you want to be using is get_stylesheet_directory_uri().
This is because get_stylesheet_directory will return the path to the stylesheet directory, which only makes sense in the context of server-side scripts, meaning it is the function you should use for things like includes.
On the other hand, get_stylesheet_directory_uri() will give you the URI of the stylesheet directory, which can be used in client-side contexts, such as linking scripts or stylesheets.

javascript file's order is not correct in drupal

Javascript file's order is not correct in Drupal. On other pages other than print page the order of script files are correct. The files are drupal.js and google_analytics_reports.js
Since the order is not correct it is causing error
"ReferenceError: Drupal is not defined"
Please help me to change the order of the files in Print pages(When we try to take a print out of the page, we will get this print page).
Are you sure that this is a problem of the js files order and not
something else?
Are the same js files loaded on print and normal pages?
What files are inside the /templates folder of your theme (or
generally files with tpl.php extension under your theme folder)?
If you just need a template for the printing mode install the print module and copy the print.tpl.php file into your theme templates folder. Then edit it as you prefer.

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