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

这一生的挚爱 提交于 2020-01-01 17:12:11

问题


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?


回答1:


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)                       \
        */                                                          \
    " );
}


来源:https://stackoverflow.com/questions/13593610/how-do-i-import-this-greasemonkey-script-that-uses-cdata-to-chrome

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!