簡體   English   中英

用Greasemonkey腳本將javascript變量與另一頁的內容進行比較?

[英]Greasemonkey script to compare a javascript variable with another page's content?

Greasemonkey腳本可以將以下腳本的Name變量與另一個站點的成員列表進行比較,如果Name與任何人都不匹配,可以使其運行腳本的其他部分嗎?

//alert(Name);
var postHistory = "http://"+regionSlice+".targetforum.com/board/search.php?do=process&searchuser="+Name+"&exactname=1&showposts=1";

var avatar = "http://othersite.com/forum/avatar/" +regionSlice+ "." + Name + ".png"; // creates an avatar

// Replace the old Avatar
$('.user_icon', this).attr('src', avatar);
$('.user_icon', this).wrap('<a href="' + postHistory + '" class="link"></a>');
$('.user_icon', this).attr('width', '80');
$('.user_icon', this).attr('height', '80');
$('.user_icon', this).attr('style', 'position:relative; TOP:7px');

如果Name與任何記錄都不匹配,則該代碼將在以下部分執行,因此非常完美。

var postHistory = "http://"+regionSlice+".targetforum.com/board/search.php?do=process&searchuser="+Name+"&exactname=1&showposts=1";
var avatar = "http://othersite.com/forum/avatar/" +regionSlice+ "." + Name + ".png"; // creates an avatar
var noAvatar = "http://other.com/forum/avatar/questionmark.png";

// Replace the old Avatar
    $('.user_icon', this).attr('src', noAvatar);
    $('.user_icon', this).wrap('<a href="' + postHistory + '" class="link"></a>');
    $('.user_icon', this).attr('width', '80');
    $('.user_icon', this).attr('height', '80');
    $('.user_icon', this).attr('style', 'position:relative; TOP:7px');

會員列表位於othersite.com/forum/members.php:

<?php
    $con = mysql_connect("host","user","pass");
    if (!$con)
    {
        die('Could not connect: ' . mysql_error());
    }
    mysql_select_db("database", $con);

    $result = mysql_query("SELECT username FROM users ORDER BY ID");

    echo "<table border='0'>
<tr>
<th>UserName</th>
</tr>";

    while($row = mysql_fetch_array($result))
    {
        echo "<tr>";
        echo "<td>" . $row['username'] . "</td>";
        echo "</tr>";
    }
        echo "</table>";

mysql_close($con);
?>

這是該頁面的示例部分。該部分在一頁中顯示1到10次,因此Name將被檢查1到10次。 “ Vortexer”是Name一個示例,下面的兩行位於user_icon

<div id="edit4767039" style="padding:0px 0px 6px 0px">
  <a name="4767039">&nbsp;</a>

  <div class="forum_post post_frame" id="post4767039">
    <div class="post_hidden_message">
       Comment below rating threshold, click <a href="#">here</a> to show it.
    </div>
    <table>
    <tr>
      <td class="left" valign="top" id="currentPost">
        <div class="avatar_top">
          <div class="avatar" style="padding-top:10px;">

            <big>Vortexer</big>
            <a class="photo">

              <img class="user_icon" src="theme/img/unknown_icon.jpg"/>
              <span class="left_orb">??</span>
              <span class="right_orb"><img src="http://irrelevantserver.com/forum/ui/avatar_right_orb_blue.png" alt=""/></span>
            </a>
            <small>Senior Member</small>
          </div>
          <center>
          <a href="//articles/The_Code" target="_blank"><span class="sca_icon" style="align: center"><img src="http://irrelevantserver.com/images/community/community site/SCA_badge.png" alt="This user has accepted the code, click for more information"/></a></span>
          </center>
        </div>
      </td>
      <td class="right" valign="top">
        <table class="right_table">
        <tr>
          <td>
            <div class="message_header">
              <!-- status icon and date -->
              <span>1 Day Ago</span>
              <!-- / status icon and date -->
            </div>
            <div class="post_content" id="post_message_4767039">
              <p>This is forum post content</p>
            </div>
            <div class="message_footer">
              <div class="r_block">
                <span class="post_rating">
                <span class="rating_positive">+3</span>
                </span>
                <a href="ratepost.php?postid=4767039&vote=-1" rel="nofollow" class="vote_down_button">
                  <img src="http://irrelevantserver.com/forum/ui/thumbs_down.png" alt=""/>
                </a>
                <a href="ratepost.php?postid=4767039&vote=1" rel="nofollow" class="vote_up_button">
                  <img src="http://irrelevantserver.com/forum/ui/thumbs_up.png" alt=""/>
                </a>
                <a href="newreply.php?do=newreply&amp;p=4767039" class="quick-reply" rel="nofollow"><img src="http://irrelevantserver.com/forum/ui/message_quote_icon.png" alt="Reply With Quote"/></a>
                <a href="editpost.php?do=editpost&amp;p=4767039" name="vB::QuickEdit::4767039"><img src="http://irrelevantserver.com/forum/ui/edit_icon.png" alt="Edit/Delete Message" class="edit_button"/></a>
              </div>
            </div>
          </td>
        </tr>
        </table>
      </td>
    </tr>
    </table>
  </div>
</div>


使用以下代碼獲取名稱:

// Replace everypost's avatar
$('.forum_post').each(function(index) {
    name = $('big', this).html();
    //alert($('big', this).html());
    var Name1 = name.replace("\<font ", "");
    var Name2 = Name1.replace("color\=\"\#c98f1a\"\>", "");
    var Name3 = Name2.replace("color=\"green\"\>", "");
    var Name4 = Name3.replace("color=\"red\"\>", "");
    var Name = Name4.replace("</font>", "");

是的,您可以將“ Name與從另一個網頁抓取的內容進行比較。 由於它看起來是跨域的,因此必須使用GM_xmlhttpRequest來執行此操作。

members.php的外觀來看,它返回一個表,如下所示:

<table>
    <tr><th>UserName</th></tr>
    <tr><td>User A</td></tr>
    <tr><td>User B</td></tr>
    <tr><td>User C</td></tr>
    <tr><td>User D</td></tr>
</table>

沒別的。
(如果確實返回其他內容,則需要調整以下代碼中的選擇器。)
在jsFiddle上制作了該HTML的模型

如果安裝此Greasemonkey腳本,則可以看到它讀取了用戶名:

// ==UserScript==
// @name        _Parse simple AJAX page scrape/fetch
// @include     http://stackoverflow.com/*
// @require     http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js
// @grant       GM_xmlhttpRequest
// ==/UserScript==

GM_xmlhttpRequest ( {
    method:     'GET',
    url:        'http://fiddle.jshell.net/TDcDV/show/',
    onload:     getUsernamesFromAjax
} );

function getUsernamesFromAjax (respObject) {
    var respDoc     = $(respObject.responseText);
    var userNameTDs = respDoc.find ("td");
    var userNames   = userNameTDs.map ( function () {
        return this.textContent;
    } ).get ();

    alert ("The usernames are: " + userNames);
}


(警告,“ The usernames are: User A,User B,User C,User D ”。)



現在,關於將Name與數據進行比較,問題尚不清楚。

  1. Name從哪里來?
  2. 有多個“ Name值嗎? 如果是這樣,哪個.user_icon節點與哪個Name

鏈接或粘貼到整個頁面。


更新:
根據新信息,以下是您希望腳本執行的操作:

  1. 用“進行中”圖像(“ throbber”)替換頭像,以使用戶知道我們正在等待AJAX​​結果。
    (AJAX可能需要幾秒鍾。)

  2. 向外部站點啟動AJAX請求以獲取成員列表。

  3. 當AJAX返回成員列表時:

    1. 對於成員列表中的名稱,請替換其頭像。
    2. 對於不在成員列表中的名稱,請使用“無頭像”圖像替換其頭像。


是完成此操作的完整腳本
安裝腳本,然后訪問jsbin.com/awaxap/1 ,以查看運行中的腳本

// ==UserScript==
// @name      _Replace avatars for matching names
// @include   http://jsbin.com/awaxap/*
// @include   http://YOUR_SERVER.COM/YOUR_PATH/*
// @require   http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js
// @resource  waitImg  http://i.cdn.turner.com/money/.element/img/1.0/misc/throbber.gif
// @grant     GM_xmlhttpRequest
// @grant     GM_getResourceURL
// ==/UserScript==

//--- Replace avatars with an "In progress" image.
var waitImgSrc  = GM_getResourceURL ("waitImg");
$("div.forum_post div.avatar img.user_icon").attr ('src',  waitImgSrc);


//--- Fetch the member list.
GM_xmlhttpRequest ( {
    method:     'GET',
    url:        'http://fiddle.jshell.net/TDcDV/show/',
    onload:     changeUserIconsOfMembers
} );


//--- Replace avatars based on name match.
function changeUserIconsOfMembers (respObject) {
    var respDoc     = $(respObject.responseText);
    var userNameTDs = respDoc.find ("td");
    var userNames   = userNameTDs.map ( function () {
        return $.trim (this.textContent.toLowerCase () );
    } ).get ();

    //--- Replace every post's avatar.
    $('div.forum_post').each ( function (index) {
        //-- text() automatically strips out any <font> cruft, if present.
        var Name        = $('div.avatar big', this). text ();
        //-- Standardize name for comparison.
        Name            = $.trim (Name).toLowerCase ();

        var regionSlice = "";   // where's this come from?
        var postHistory = "http://" + regionSlice
                        + ".targetforum.com/board/search.php?do=process&searchuser="
                        + Name + "&exactname=1&showposts=1"
                        ;
        var avatar      = "http://othersite.com/forum/avatar/" + regionSlice
                        + "." + Name + ".png"
                        ; // creates an avatar

        avatar  = "http://i.stack.imgur.com/Nrzn7.jpg"; // Temp avatar upgrade. ;)

        //--- Was the username not found?
        if (userNames.indexOf (Name) === -1 ) {
            avatar      = "http://other.com/forum/avatar/questionmark.png";
            avatar  = "http://i.stack.imgur.com/BbOsC.gif"; // Temp avatar upgrade. ;)
        }

        //--- Replace the old Avatar and give it a link to history.
        var userIcon    = $('div.avatar img.user_icon', this);
        userIcon.attr ( {
            src:        avatar,
            width:      '80',
            height:     '80',
            style:      'position:relative; TOP:7px;'
        } );
        userIcon.wrap ('<a href="' + postHistory + '" class="link"></a>');
    } );
}


請注意,找不到用戶“ Vortexer”,但找到了“用戶B”。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM