Implementing Gatsby-js for client-side JavaScript directly within a blog post is a powerful

I've been working on setting up a blog using Gatsby-JS and have run into a bit of an issue. My posts, written in markdown, include inline javascript like this:

<script>window.alert("hello");</script>

When I test the site with "Gatsby serve", the script doesn't execute when I visit my post from the blog index. Strangely, there are no errors in the web console.

However, if I navigate directly to the post page or refresh the page (F5 or ctrl+f5), the alert pops up as expected.

After deploying the site to GitHub Pages, I noticed a change in behavior. Even refreshing or navigating from the index doesn't trigger the script. Only after pressing ctrl+F5 does it work.

If you'd like to see a live test example, you can check out my blog here. It showcases multiple alerts and attempts to load Plotly.

Answer №1

Successfully implemented Dinne's solution. Great job! :)

I had to find an alternative to JQuery, so here is a version that doesn't rely on it:

componentDidMount() {

  // Allow in-line JS scripts to be executed
  let scripts = document.querySelectorAll('[data-inline-script="data-inline-script"]');
  scripts.forEach(function executeScript(element) {
    const script = element.innerHTML;
    window.eval(script);
});

This code snippet works with the following HTML:

<script data-inline-script="data-inline-script">
    console.log("this works");
</script>

I am using this approach on a simple static website. Although I'm not a fan of using eval(), it serves its purpose without harm in my case.

Update While the above solution functions, I encountered issues when trying to include external scripts using <script src="...">, which didn't work :( This workaround feels somewhat makeshift as well.

Answer №2

Take a look at this question React: Script tag not working when inserted using dangerouslySetInnerHTML

The issue arises when trying to execute scripts in HTML that is inserted through React's dangerouslySetInnerHTML. A helpful workaround is provided in the linked question, which you may find useful.

Answer №3

The guidance provided by the previous response was instrumental in helping me find my way.

To solve the issue, I assigned the attribute data-my-script to all inline scripts and then made modifications to layouts/index.jsx (not html.jsx since it is only rendered on the server side).

componentDidMount() {
    let scripts = window.jQuery.find('[data-my-script]')
    console.log(scripts);
        scripts.forEach(function forEachScript(element) {
            const script = window.jQuery(element).text();
            window.eval(script);
        });

  }

  render() {
    const { children } = this.props;
    return (
      <Navigation config={config} LocalTitle={this.getLocalTitle()}>
        <div ref={contentElement => (this.contentElement = contentElement)}>
          <Helmet>
            <meta name="description" content={config.siteDescription} />
            // for plotly inside notebooks
            //  <script src="https://cdn.plot.ly/plotly-latest.min.js" />
            <script src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.3.5/require.min.js"/>
            <script src="https://code.jquery.com/jquery-3.2.1.min.js"/>
          </Helmet>
          {children()}
        </div>
      </Navigation>
    );
  }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Encountering issue with 'mongodb-connection-string-url'

As a beginner, I am struggling to understand the error message. When I try to run the app.js file, I receive the following log message. I read that I need to upgrade my MongoDB, but since I am using Windows 7, this seems impossible. PS G:\AWebDev&bsol ...

What is the best way to use createElement in JavaScript to insert <p> and <span> elements within a <div>?

I am currently experimenting with generating sentences accompanied by draggable text boxes. To achieve this, I intend to construct the following HTML structure using JavaScript exclusively: <div> <p>Data1<span class = "smallBox droppabl ...

Is it possible to create two header columns for the same column within a Material UI table design?

In my Material UI table, I am looking to create a unique header setup. The last column's header will actually share the same space as the previous one. Picture it like this: there are 4 headers displayed at the top, but only 3 distinct columns undern ...

Contentful integrated into a NuxtJs website

After successfully creating a blog using Nuxt JS and integrating Contentful into the project, I followed a helpful tutorial from here. This enabled me to retrieve all sections such as title, date, and content of the post efficiently. However, I am current ...

Script injection causing Vue bundle to fail executing

I am developing a Vue widget that can be embedded using @vue/cli. The idea is to provide users with a code snippet to insert into their website: <script src="https://test.com/embed.unique.js"></script> This script initializes the roo ...

Modify the hyperlink address in the body of the webpage using jQuery

I'm searching for a solution to modify the href attribute in the following code: <link rel="stylesheet" type="text/css" href="theme1.css"> For instance, changing it from: <link rel="stylesheet" type="text/css" href="theme1.css"> to: & ...

The function initiates without delay upon meeting the specified condition

I am looking to trigger a function automatically upon certain dynamically changing conditions in my JavaScript code. I attempted using the document.body.onload method, but it did not work as expected. document.body.onload = myFunction() function myFunct ...

Function in Typescript that can return multiple data types

I recently started learning about TypeScript and its concepts. During my practice sessions, I encountered a problem that left me puzzled. There is a function named `functionA` which returns an object based on the response received from an API. type Combina ...

retrieve HTML content by its ID stored in a variable

In my JavaScript code, I have a variable named "value" that contains HTML data. I am trying to extract the data from a specific ID that is located within the element with ID #myDiv. var value="<div > <p class="">Hi <a href="/ ...

What is the best way to add a filter to a nested array?

I am currently facing a challenge in creating a multiple filter for multiple arrays without duplicating the nested array. I am working with vuejs and some plugins that are relying on the array, so my only option is to filter it without modifying it. Using ...

WebStorm not recognizing NodeJS Core Modules in External Libraries

As a newcomer to NodeJS and WebStorm, I am currently diving into a tutorial on creating an Express app. In the tutorial, the instructor always gets prompted with "Configure NodeJS Core Module Sources" including the URL nodeJS.org when creating a new NodeJ ...

Steps for showcasing a automated slideshow

I'm currently working on creating a slideshow that automatically displays multiple images. While the first image shows up just fine, it doesn't seem to transition to the next one. var currentSlide = 0; displaySlides(); functio ...

The problem of having an undefined state in Vuex arises

https://i.stack.imgur.com/52fBK.png https://i.stack.imgur.com/GcJYH.jpg There is an error occurring: TypeError: Cannot read property 'state' of undefined ...

Iterating through elements to set the width of a container

I am currently working on a function that dynamically adjusts the width of an element using JavaScript. Here is my JavaScript code: <script> $('.progress-fill span').each(function(){ var percent = $(this).html(); if(per ...

Transition smoothly from the first texture to a solid color, and then seamlessly switch to the second texture using a GLSL Shader

I am working on a GLSL fragment shader that aims to achieve the following sequential effects: Transition from texture 1 to a specific color Transition from the color to texture 2 Here's my initial attempt: // Uniforms uniform sampler2D tex1; uniform ...

Create a function that will repeatedly call itself at specified intervals, increment a variable, and update the class values of elements with an id matching the current value of the

I'm attempting to create a setup that cycles through different images <div id="img_box" class="shadow" onload="imgCycle(1)";> <img id="1" class='opaque imgbox selected' src="media/img ...

Implement functionality in JS to track the number of clicks on an element

I am dealing with a ul-list containing an unpredictable number of li-elements, ranging from 2 to 8. My goal is to capture votes using these li-elements and display the vote count on the specific element that was clicked. I have attempted to catch the click ...

How to Retrieve Superclass Fields in Angular 5 Component

I have a superclass that provides common functionality for components. export class AbstractComponent implements OnInit { public user: User; constructor(public http: HttpClient) { } ngOnInit(): void { this.http.get<User>(& ...

Insert an element at the start of a sorted array object

I am currently working on a small application that has the following structure: Posts -> Post -> Comments -> Comment. The Posts component sends a request for an array of posts sorted by date in descending order. Each post also fetches its comment ...

Modifications to contenteditable elements result in a change to their IDs

Having some trouble with the behavior of a contenteditable div. The code structure is like this: <div contenteditable="true"> <p id="element-id-1">element-id-1</p> <p id="element-id-2">element-id-2</p> </div> E ...