How to embed inline javascript in Drupal, anywhere on any page

“Inline JavaScript is highly discouraged” it says on the Adding Javascript to a Drupal module page.

It’s good advice.
But what if integrating that third-party tool or widget requires you to do it?

Moreover, what if that inline javascript requires it to be embedded right there where you need that widget to appear on your page, be that left, right or centre?

And what if the actual <script> tag needs to point to a file hosted on a server that the Drupal site builder enters through the UI, on some configuration page?

Our use-case was to seamlessly embed a Vanilla Forum, anywhere on any Drupal page.

In researching this I came across solutions that employ advanced trickery, sometimes employing Drupal’s theming layer, and Twig. Some solutions incorporated multiple files.
The Drupal manual page quoted above, offers hook_page_attachments() as a last resort.

None of these solutions were cutting it for our client. The solution below did.

To allow the site builder flexibility as to where they want the javascript to be inserted, we used a block. It’s easy to programmatically create a block in Drupal. It will appear in the block UI, and can then be dropped into any region on the page. The block’s visibility can be set so it appears on just one page or on multiple pages (URLs).

This is the kind of stock standard block plugin PHP code for creating a Drupal block (annotation omitted):

You can see from the code above it caters for embedding a JS <script> tag.
As the block can be placed in any region of the page, its contents, i.e. its embedded javascript, will move with it accordingly. Hence your widget (in our case the Vanilla Forum) can be placed top, centre, bottom of the page, or even in a side bar, if that looks good on your site.

“But wait!”, I hear you say. “That script code will be filtered out during rendering by Xss::filterAdmin(), which strips dangerous XSS vectors.”
Indeed it does.

So here’s the trick to prevent Drupal from doing that, just for this one block. You add ‘#allowed_tags’ => [‘script’].

And that does the trick!

The javascript file may live anywhere, including on a different site. The code example above shows that using this method, it is easy to make the location of the JS configurable by pulling the URL in from a Drupal setting, named js_file_url in the example above.

Instead of a script tag pulling in a file, you can also inline JS code directly. Changing the $tag assignment above to

will pop up an alert — no problem.

The actual block code we used to embed Vanilla Forums can be found here.

Software developer, entrepreneur, happy mapper.

Software developer, entrepreneur, happy mapper.