2011-06-11 78 views
3

JScript在大多數日子裏都做了我的工作,但設計不佳的網站更是如此。 Foursquare就其超級用戶而言就是這樣一個例子。更新頁面使用Greasemonkey添加新鏈接

期望的結果

Greasemonkey的腳本,將尋找通過DIV類信息搜索結果的每次出現,和DIV類名後追加了兩個新的A HREF元素類似以下:

<a href="/venue/venueid/edit">Manage venue</a> <a href="/edit_venue?vid=venueid">Edit venue</a> 

Scenairo

我想用Greasemonkey讓他們的超級用戶的生活變得更容易一些。其目的是修改網站上的特定頁面(https://foursquare.com/search),並添加大量額外鏈接以直接跳轉到場地的特定頁面,以使工作流程更快。

我已經找過四處尋找如何做到這一點的示例(通過反向工程學習),但是如果我應該使用RegEx或其他東西,我會遇到困難。

在搜索結果頁面(https://foursquare.com/search?q=dump&near=Perth%2C+Australia),有返回地點的完整列表。對搜索結果中返回每個場館的代碼看起來就像這樣:

<div class="searchResult"> 
      <div class="icon"><img src="https://4sqstatic.s3.amazonaws.com/img/categories/parks_outdoors/default-29db364ef4ee480073b12481a294b128.png" class="thumb" /></div> 
      <div class="info"> 
       <div class="name"><a href="/venue/4884313">Staff Smoking Spot/Dumpster Dock</a></div> 
       <div class="address"><span class="adr"></span></div> 

       <div class="specialoffer"></div> 

      </div> 

      <div class="extra"> 
       <div class="extra-tip"><div><a href="/venue/4884313">0 tips</a></div></div> 
       <div class="extra-checkins"><div>10 check-ins</div></div> 
      </div> 
      </div> 

工作至今

四處尋找答案,這就是我想出了(如下圖)。不用說,它沒有檢測到它需要在什麼地方插入A HREF元素,並且不會遍歷頁面上輸出的所有元素,更不用說構建正確的鏈接。

// First version 
var elmNewContent = document.createElement('a'); 
elmNewContent.href = sCurrentHost; 
elmNewContent.target = "_blank"; 
elmNewContent.appendChild(document.createTextNode('edit venue')); 
var elmName = document.getElementById('name'); 
elmName.parentNode.insertBefore(elmNewContent, elmName.nextSibling); 
+0

是,「管理場所」鏈接是否正確?我得到一個404,嘗試它。 – 2011-06-11 05:57:14

+0

是的,鏈接是正確的。據我瞭解,安全系統旨在拒絕未授權方(具有所需訪問級別的用戶,特別是未經驗證的用戶)使用ol'404錯誤。 – thewinchester 2011-06-11 21:59:38

回答

4

這很簡單,使用jQuery。
這裏是整個腳本,因爲它是一個5分鐘的工作...

// ==UserScript== 
// @name  _Square away foursquare 
// @include http://foursquare.com/* 
// @include https://foursquare.com/* 
// @require http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js 
// @grant GM_addStyle 
// ==/UserScript== 

var SearchRezLinks = $("div.searchResult div.name > a"); 

/*--- Link is like: <a href="/venue/6868983">Dumpling King</a> 
    where 6868983 is venue ID. 

    Want to add: <a href="/venue/venueid/edit">Manage venue</a> 
    <a href="/edit_venue?vid=venueid">Edit venue</a> 
*/ 
SearchRezLinks.each (function() { 

    var jThis  = $(this); 
    var venueID  = jThis.attr ('href').replace (/\D+(\d+)$/, '$1'); 
    jThis.parent().append ('<a href="/venue/' + venueID + '/edit">Manage venue</a>'); 
    jThis.parent().append ('<a href="/edit_venue?vid=' + venueID + '">Edit venue</a>'); 
}); 

GM_addStyle ("         \ 
    div.searchResult div.name > a + a {   \ 
     font-size:  0.7em;     \ 
     margin-left: 2em;     \ 
    }           \ 
");            
+1

布洛克,你是一個血腥的傳奇人物。我什至沒有想到使用jQuery來做這個* facepalm *。 – thewinchester 2011-06-11 10:53:58