脚本无意中起作用

时间:2013-09-16 08:08:51

标签: javascript

此脚本(对于Greasemonkey)无意中有效 我想插入一个脚本,在加载脚本后,将文本“Download”替换为日语单词(我将使用“TEST”代替。)。

(function() {
    if ((document.URL.match("www.youtube.com/watch?"))||(document.URL.match("c.youtube.com/videoplayback?"))) {
    var head = document.getElementsByTagName('head')[0]; //Working
    var script = document.createElement('script'); //Working
    script.type = 'text/javascript'; //Working
    script.src = 'http://userscripts.org/scripts/source/25105.user.js'; //Working
    script.onload = 'document.getElementsByClassName("yt-uix-button-content")[0].innerHTML.replace("Download","TEST")'; //Not working.
    head.appendChild(script); //Working
};})();

有什么问题?

1 个答案:

答案 0 :(得分:0)

您必须确保已加载元素。 这意味着,在加载正文内容后,您可以查询正文中的元素。 这导致以下解决方案。 在BODY标签上,你必须添加以下

<body onload="myOnloadFunc()">

然后你必须按如下方式创建myOnloadFunc:

<script type="text/javascript>
function myOnloadFunc () {

  // in here you should place the original code you have created.

  if ((document.URL.match("www.youtube.com/watch?"))|| (document.URL.match("c.youtube.com/videoplayback?"))) {
     var head = document.getElementsByTagName('head')[0]; //Working
     var script = document.createElement('script'); //Working
     script.type = 'text/javascript'; //Working
     script.src = 'http://userscripts.org/scripts/source/25105.user.js'; //Working
     script.onload = 'document.getElementsByClassName("yt-uix-button-content")[0].innerHTML.replace("Download","TEST")'; //Not working.
     head.appendChild(script); //Working
}
</script>