Drupal Content Management System Tip - Adding Inline Javascript to Drupal Node

Adding Inline Javascript to a Single Drupal Node

by Dixie

WP Greet Box icon
Hello there! If you are new here, you might want to subscribe to the RSS feed or get email updates. Cool, man!

You wouldn’t think something that should be so easy as adding a script to a page would require a trip to the Drupal API documentation. But Drupal, like most Content Management Systems, has security systems in place to filter most javascript during submission so site members can’t do ugly things via scripting. In most cases, that’s a good thing. When you’re scratching your head trying to figure out a way around it, not so much.

You can hard-code a script into the template, if you need it on all the pages and it works. But just adding a a single, inline javascript into a Drupal node was much harder than I expected. Since I wasted plenty of my own precious time figuring out a workable approach for this–don’t laugh, you coders!–I thought I’d share it with others. Maybe it can save you from feeling foolish.

It’s easy – as 1, 2, 3! First,  put the script on your server, someplace it’s easy to find. I opted to make a “scripts” folder in my sites/all folder in the Drupal installation because I knew that’s where I’d be most likely to look for it later. Y’kno. In case you get lazy with the documentation. (But you’d never do that, right? Ha!)

Second, when do your post, set your input filter to PHP, and third, do a php include where you’d like to place the script. Something like this:

<?php include('sites/all/scripts/my_javascript.js'); ?>

That’s it! You now have instant javascript, with no API-scouring-induced drowsiness. Happy Drupalling!

Possibly Related

Posted on October 9, 2009 at 1:33 pm in: Tech Help

{ 2 comments… read them below or add one }

Hugo Minney February 18, 2010 at 12:54 am

I’d go one stage further (Drupal 6.14). The PHP filter seems to have been removed, so go to administer >> site configuration >> input formats >> add input format, and add a new input format (available to NO roles – administrators can use all filters) with no filters checked.
This will then run javascript. this means you can update the page in the usual node editing window instead of uploading a file.
Of course it represents a security risk, and you need to test your code carefully before uploading.

Reply

Dixie February 26, 2010 at 12:20 pm

Thanks for the addition, Hugo. I haven’t worked with Drupal 6 yet, so have yet to experience the horror of not having access to straight PHP filter.

While I utterly understand and appreciate the need for security, I hate having my hands tied behind my back in trying to whip sites into submission.

Reply

Leave a Comment

Previous post:

Next post: