Search code examples
wordpressiis-10windows-server-2019cloudflare-workers

JavaScript Errors After Changing Servers (Wordpress)


I moved a Wordpress site to a new server. I did this by directly copying the folder to the new server. The web server is IIS 10.0 and the PHP version is 7.4.13. When editing a Post, I noticed that I wasn't able to add an image from the Gallery. I also a weird JavaScript error, which doesn't happen on the old server. The error relates to thickbox.js:

enter image description here

The error in the console is

Uncaught SyntaxError: missing ) after argument list

The strange thing is that the original file doesn't contain &quot:

enter image description here

I've compared the IIS configurations and I don't see any difference. Nothing else has changed, the wp-config.php file is the same as is the database. Has anyone else experienced a similar issue?

I came across this question, however this relates to the content of the post - which isn't my issue.

Update 2021/08/19

Something that I didn't think could have caused this issue was a Cloudflare Worker active on the route. Initially this was just to perform 301 redirects based on url's stored in KV. Following the server change, I added some code to update some old url's and ensure https was used. When I removed the Worker, the JavaScript errors disappeared. I then tracked the issue to the HTMLRewriter I was using (code is below). I just not sure why the replace method is causing the issue?

class AttributeRewriter {
  constructor(attributeName) {
    this.attributeName = attributeName
  }

  element(element) {
    const attribute = element.getAttribute(this.attributeName)
    
    if (attribute) {
      let newValue = attribute.replace(new RegExp(blogOriginUrl, 'g'), blogPublicUrl).replace(new RegExp(csOriginUrl, 'g'), csPublicUrl).replace(new RegExp(httpUrl, 'g'), httpsUrl)

      element.setAttribute(this.attributeName, newValue)
    }
  }
}

const urlRewriter = new HTMLRewriter().on('a', new AttributeRewriter('href')).on('img', new AttributeRewriter('src')).on('img', new AttributeRewriter('srcset'))

Solution

  • The problem is that your worker is using HTMLRewriter to rewrite resources that are not actually HTML. In this case, it is rewriting a JavaScript file. HTMLRewriter assumes whatever input you give it is HTML, and attempts to parse it as such. Here, it has seen the <img> tag appearing in your JavaScript, and it thinks that's an HTML tag. It has parsed the tag, then written it out again in a slightly different way, which is valid for HTML but not correct for JavaScript.

    In your worker, you need to make sure that you only apply HTMLRewriter to responses that are actually HTML, based on Content-Type. Like:

    if (response.headers.get("Content-Type").startsWith("text/html")) {
      // apply HTMLRewriter here
    }