Search code examples
javascriptgoogle-chromegreasemonkeyuserscriptse4x

How do I import this Greasemonkey script, that uses CDATA, to Chrome?


I've got following code that works fine on Greasemonkey but not in Chrome:

// ==UserScript==
// @name        SO
// @namespace   stackoverflow.com
// @include     *stackoverflow.com/*
// @version     1
// ==/UserScript==

changeHeaderColor();

function changeHeaderColor()
{
GM_addStyle((<><![CDATA[
   //body { color: white; background-color: black }
   #custom-header       {background-color: rgb(251,122,35)}

   #nav-questions       {background-color: rgb(251,122,35)}
   #nav-tags            {background-color: rgb(251,122,35)}
   #nav-users           {background-color: rgb(251,122,35)}
   #nav-badges          {background-color: rgb(251,122,35)}
   #nav-unanswered      {background-color: rgb(251,122,35)}
   #nav-askquestion     {background-color: rgb(251,122,35)}
   //Blau: rgb(0,160,160) rgb(0,200,200)
    ]]></>).toString());
}


What do I have to change so that it will work on Chrome or just even both?


Solution

  • That <><![CDATA[ ... ]]></> code uses "EX4", which was never supported by Chrome and will soon not be supported by Firefox, either.

    So, to get that script to work, you need to use a a different method for multiline strings in javascript. Also, for Greasemonkey, you should supply a @grant value, as of GM 1.0.

    User the \ escape character and be very careful with " and ' quotes.
    Also, do not use // comments in such strings, as they will stop everything after them, even if it looks like it's on a new line.

    It ain't pretty, but this will do it:

    // ==UserScript==
    // @name        SO
    // @namespace   stackoverflow.com
    // @include     *stackoverflow.com/*
    // @version     1
    // @grant       GM_addStyle
    // ==/UserScript==
    
    changeHeaderColor ();
    
    function changeHeaderColor () {
        GM_addStyle ( "                                                 \
            /*body { color: white; background-color: black }            \
            */                                                          \
            #custom-header       {background-color: rgb(251,122,35)}    \
                                                                        \
            #nav-questions       {background-color: rgb(251,122,35)}    \
            #nav-tags            {background-color: rgb(251,122,35)}    \
            #nav-users           {background-color: rgb(251,122,35)}    \
            #nav-badges          {background-color: rgb(251,122,35)}    \
            #nav-unanswered      {background-color: rgb(251,122,35)}    \
            #nav-askquestion     {background-color: rgb(251,122,35)}    \
            /*Blau: rgb(0,160,160) rgb(0,200,200)                       \
            */                                                          \
        " );
    }