Javascript Script tag removed from custom token?

Created on 28 March 2024, 6 months ago

Problem/Motivation

I am using the Metatag module and in the field "Expire", it requires value in GMT format to show when the page will expire.
To make it dynamic and into a future date, I am using the custom token module and entering javascript like this:

<script type="text/javascript">
const now = new Date();
const tomorrow = new Date(now.getFullYear(), now.getMonth(), now.getDate() + 3, now.getHours(), now.getMinutes(), now.getSeconds());
const rfc1123DateString = tomorrow.toUTCString();

document.write(rfc1123DateString);
</script>

I created a new custom token type called "cache-expire" using this code.
So this token was created: "[cache-expires:3day]" using the code above and I added this token to the metatag module in the "expire" field.

Problem is that the javascript is not processed so the actual token shows the javascript code and not the actual GMT format date. The script tags are automatically removed and not processed.

Is the custom token module causing this or is the metatag module causing this?

It seems like this was an issue a while ago? If this is the same issue, can we make it work with the latest 2.0 version?
https://www.drupal.org/project/metatag/issues/3030181 β†’

How else can I add a future date on the expire field if it won't take JavaScript and Drupal 10 no longer supports PHP text format?
Any assistance on the matter would be greatly appreciated.

πŸ› Bug report
Status

Closed: works as designed

Version

2.0

Component

Code

Created by

πŸ‡ΊπŸ‡ΈUnited States jsidigital

Live updates comments and jobs are added and updated live.
Sign in to follow issues

Comments & Activities

  • Issue created by @jsidigital
  • Status changed to Closed: works as designed 6 months ago
  • πŸ‡ΊπŸ‡ΈUnited States DamienMcKenna NH, USA

    Metatag generates the output server-side. Part of that is a filter to make sure no unwanted code is added to the output, specifically that no JavaScript is added. So the JavaScript tag you're trying to add is removed when it's building the output.

    Even if the JS wasn't removed, this is how it would render:

    <meta name="expires" content="<script type="text/javascript">
    const now = new Date();
    const tomorrow = new Date(now.getFullYear(), now.getMonth(), now.getDate() + 3, now.getHours(), now.getMinutes(), now.getSeconds());
    const rfc1123DateString = tomorrow.toUTCString();
    
    document.write(rfc1123DateString);
    </script>">

    This isn't valid HTML and wouldn't work the way you think it should.

    I'm not sure what the correct approach is to get a correct value for the tag, other than maybe to look at a different mechanism, e.g. using page caching and making sure Drupal's Expires HTTP header is correct.

Production build 0.71.5 2024