编程语言
首页 > 编程语言> > 使用Greasemonkey脚本将javascript添加到使用XSLT转换的XML文件中

使用Greasemonkey脚本将javascript添加到使用XSLT转换的XML文件中

作者:互联网

在这里继续我的问题-How to transform an XML file with XSLT, using a Greasemonkey script?-我面临另一个问题:

我想在XSL模板中使用一些基本的javascript函数,以控制某些div的显示.但是,无论我如何包括这些javascript函数,它们似乎都无法被识别.我已经进行了很多研究,但似乎无法解决.

我尝试了两件事:

>在XSL模板中的< script>中添加javascript.标签
>附加新的< script> Greasemonkey脚本本身中的标签

我不希望使用jQuery或外部JS文件(我也尝试过)以使其尽可能简单,但是如果这样可以解决问题,我愿意改变整个事情!

无论哪种情况,当我调用函数时,都会得到ReferenceError:x未定义.我确实看到javascript代码很好地位于了最终的HTML结果中.当我使用Firebug附加新的< script>标记具有一个简单的功能,可以向“您好”提示纯HTML页面,然后完美运行.只有在XSLT转换之上完成此操作时,事情才会出错(为简单起见,我仅使用一个简单的函数来显示警报框).

这是我的示例数据:

  <?xml version="1.0" encoding="utf-8"?>
  <Results>
      <Result>
          <Listings total="2">
              <Res>
                  <Result index="0">
                      <id>123456</id>
                      <name>My Business</name>
                      <category>Restaurants</category>
                      <phone>9872365</phone>
                  </Result>
              </Res>
              <Res>
                  <Result index="1">
                      <id>876553</id>
                      <name>Some Other Business</name>
                      <category>Restaurants</category>
                      <phone>9834756</phone>
                  </Result>
              </Res>
          </Listings>
      </Result>
  </Results>

这是我刚刚添加< script> < head>中的标签标签:

// ==UserScript==
// @name        _Test XML Renderer
// @description stylesheet for xml results
// @include     *
// @grant       none
// ==/UserScript==

var xsl_str = '<?xml version="1.0" encoding="utf-8"?>\n\
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">\n\
    <xsl:output method="html"/>\n\
    <xsl:template match="/">\n\
        <html>\n\
            <head><script type="text/javascript">function hello() {alert("hello")};</script></head>\n\
            <body>\n\
                <table id="results" border="1" cellspacing="0" cellpadding="0">\n\
                    <thead>\n\
                        <tr>\n\
                            <th class="name">id</th>\n\
                            <th class="name">category ID</th>\n\
                            <th class="name">name</th>\n\
                            <th class="name">phone</th>\n\
                        </tr>\n\
                    </thead>\n\
                    <tbody>\n\
                        <xsl:for-each select="Results/Result/Listings/Res">\n\
                            <tr>\n\
                                <td class="small" width="120">\n\
                                    <a href="#" onclick="hello()"><xsl:value-of select="Result/id"/></a>\n\
                                </td>\n\
                                <td class="small" width="120">\n\
                                    <xsl:value-of select="Result/category"/>\n\
                                </td>\n\
                                <td class="small" width="120">\n\
                                    <xsl:value-of select="Result/name"/>\n\
                                </td>\n\
                                <td class="small" width="120">\n\
                                    <xsl:value-of select="Result/phone"/>\n\
                                </td>\n\
                            </tr>\n\
                        </xsl:for-each>\n\
                    </tbody>\n\
                </table>\n\
            </body>\n\
        </html>\n\
    </xsl:template>\n\
</xsl:stylesheet>\n\
';

var processor   = new XSLTProcessor ();
var dataXSL     = new DOMParser ().parseFromString (xsl_str, "text/xml");

processor.importStylesheet (dataXSL);

var newDoc      = processor.transformToDocument (document);

//-- These next lines swap the new, processed doc in for the old one...
window.content  = newDoc;

document.replaceChild (
    document.importNode (newDoc.documentElement, true),
    document.documentElement
);

这是我在XSL模板之外添加“ hello”功能的其他尝试:

// ==UserScript==
// @name        _Test XML Renderer
// @description stylesheet for xml results
// @include     *
// @grant       none
// ==/UserScript==

var xsl_str = '<?xml version="1.0" encoding="utf-8"?>\n\
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">\n\
    <xsl:output method="html"/>\n\
    <xsl:template match="/">\n\
        <html>\n\
            <head></head>\n\
            <body>\n\
                <table id="results" border="1" cellspacing="0" cellpadding="0">\n\
                    <thead>\n\
                        <tr>\n\
                            <th class="name">id</th>\n\
                            <th class="name">category ID</th>\n\
                            <th class="name">name</th>\n\
                            <th class="name">phone</th>\n\
                        </tr>\n\
                    </thead>\n\
                    <tbody>\n\
                        <xsl:for-each select="Results/Result/Listings/Res">\n\
                            <tr>\n\
                                <td class="small" width="120">\n\
                                    <a href="#" onclick="hello()"><xsl:value-of select="Result/id"/></a>\n\
                                </td>\n\
                                <td class="small" width="120">\n\
                                    <xsl:value-of select="Result/category"/>\n\
                                </td>\n\
                                <td class="small" width="120">\n\
                                    <xsl:value-of select="Result/name"/>\n\
                                </td>\n\
                                <td class="small" width="120">\n\
                                    <xsl:value-of select="Result/phone"/>\n\
                                </td>\n\
                            </tr>\n\
                        </xsl:for-each>\n\
                    </tbody>\n\
                </table>\n\
            </body>\n\
        </html>\n\
    </xsl:template>\n\
</xsl:stylesheet>\n\
';

var processor   = new XSLTProcessor ();
var dataXSL     = new DOMParser ().parseFromString (xsl_str, "text/xml");

processor.importStylesheet (dataXSL);

var newDoc      = processor.transformToDocument (document);

var script = "function hello() {alert('hello')};";
var newElem = newDoc.createElement('script');
newElem.type = 'text/javascript';
newElem.appendChild(newDoc.createTextNode(script));
newDoc.getElementsByTagName('head').item(0).appendChild(newElem);

//-- These next lines swap the new, processed doc in for the old one...
window.content  = newDoc;

document.replaceChild (
    document.importNode (newDoc.documentElement, true),
    document.documentElement
);

解决方法:

Don’t use onclick.这对用户脚本来说是三倍,因为存在其他范围和/或沙箱冲突.

另外,尝试将JS添加到XSLT文件/文本中也是一个糟糕的主意,在这种情况下也不需要脚本注入.

使用脚本来执行您需要考虑的所有JS操作.例如:

// ==UserScript==
// @name        _XML Renderer with javascript functionality
// @description Stylesheet and javascript for xml results
// @include     http://YOUR_SERVER.COM/YOUR_PATH/*.xml
// @resource    xslFile  Q_17998446_transform.xsl
// @grant       GM_getResourceText
// ==/UserScript==

var xsl_str     = GM_getResourceText ("xslFile");
var processor   = new XSLTProcessor ();
var dataXSL     = new DOMParser ().parseFromString (xsl_str, "text/xml");

processor.importStylesheet (dataXSL);

var newDoc      = processor.transformToDocument (document);

//-- These next lines swap the new, processed doc in for the old one...
window.content  = newDoc;

document.replaceChild (
    document.importNode (newDoc.documentElement, true),
    document.documentElement
);

//-- Use JS to smarten-up the new document.
var firstCols   = document.querySelectorAll ("#results td:first-child");

for (var J = firstCols.length - 1;  J >= 0;  --J) {
    var tdNode = firstCols[J];
    tdNode.style.cursor = "pointer";
    tdNode.addEventListener ("click", clickCellHandler, false);
}

function clickCellHandler (zEvent) {
    var cellContents = zEvent.target.textContent.trim ();

    alert ('The clicked cell contains "' + cellContents + '".');
}

其中Q_17998446_transform.xsl是保存在安装脚本的同一文件夹中的文件(可能需要卸载并重新安装脚本).

Q_17998446_transform.xsl包含以下内容:

<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
    <xsl:output method="html"/>
    <xsl:template match="/">
        <html>
            <head></head>
            <body>
                <table id="results" border="1" cellspacing="0" cellpadding="0">
                    <thead>
                        <tr>
                            <th class="name">id</th>
                            <th class="name">category ID</th>
                            <th class="name">name</th>
                            <th class="name">phone</th>
                        </tr>
                    </thead>
                    <tbody>
                        <xsl:for-each select="Results/Result/Listings/Res">
                            <tr>
                                <td class="small" width="120">
                                    <xsl:value-of select="Result/id"/>
                                </td>
                                <td class="small" width="120">
                                    <xsl:value-of select="Result/category"/>
                                </td>
                                <td class="small" width="120">
                                    <xsl:value-of select="Result/name"/>
                                </td>
                                <td class="small" width="120">
                                    <xsl:value-of select="Result/phone"/>
                                </td>
                            </tr>
                        </xsl:for-each>
                    </tbody>
                </table>
            </body>
        </html>
    </xsl:template>
</xsl:stylesheet>

当您在适当的XML文件上运行该脚本时,它将单击处理程序添加到第一表列(无标题)中,即“ Web 2.0”方式.

单击第一列单元格之一时,它会发出警报,例如:

The clicked cell contains “876553”.

标签:greasemonkey,xml,xslt,javascript
来源: https://codeday.me/bug/20191122/2063768.html