在Chrome新闻阅读器扩展中打开标签页

时间:2012-01-28 21:17:50

标签: google-chrome-extension

我正在尝试使用以下Google RSS阅读器示例创建一个简单的Chrome扩展程序

http://code.google.com/chrome/extensions/samples.html#597015d3bcce3da693b02314afd607bec4f55291

我可以在打开标签的弹出窗口中添加链接,但不能从Feed本身添加链接。

循环播放Feed中的项目,抓取标题标记和链接标记,我希望标题链接到相应的网站

      var entries = doc.getElementsByTagName('item');

      var count = Math.min(entries.length, maxFeedItems);
      for (var i = 0; i < count; i++) {
        item = entries.item(i);

        // Grab the title for the feed item.
        var itemTitle = item.getElementsByTagName('title')[0];
        if (itemTitle) {
          itemTitle = itemTitle.textContent;
        } else {
          itemTitle = "Unknown title";
        }

      // Grab the link for this feed item
      var itemLink = item.getElementsByTagName('link')[0];
      if (itemLink) {
          itemLink = itemLink.textContent;
        } else {
          itemLink = "Unknown link"; 
        }


        var title = document.createElement("a");
        title.className = "item_title";
        title.innerText = itemTitle; //display title in iframe

        title.addEventListener("click", titleLink); // should open link when clicking on title, but does not.
      }

    // -------------------------------------------------------------------

    // Show |url| in a new tab.
    function showUrl(url) {
      // Only allow http and https URLs.
      if (url.indexOf("http:") != 0 && url.indexOf("https:") != 0) {
        return;
      }
      chrome.tabs.create({url: url});
    }

function moreStories(event) {
  showUrl(moreStoriesUrl);
}

function titleLink(event) {
showUrl(itemLink);
}

有关为什么不起作用的任何想法。

如果我替换title.addEventListener(“click”,titleLink); with title.addEventListener(“click”,moreStories);每个标题都链接到moreStories,我无法将每个标题链接到itemLink。

由于

2 个答案:

答案 0 :(得分:0)

如果没有完整的代码,有点难以回答你的问题,但我会试一试;)
首先,titleLink()不会起作用,因为itemLink是未知的。当您创建标题(链接)时,您应该将其附加到... ...说title.href=itemLink然后在tiltleLinks中您可以使用showUrl(event.currentTarget.href)访问该href 你也修复了那个例子中的错误吗?...如果没有,那么将frameLoaded改为....

function frameLoaded() {
  var links = document.getElementsByTagName("A");
  for (i = 0; i < links.length; i++) {
    var clssName = links[i].className;
    if (clssName != "item_title" && clssName != "open_box") {
      links[i].addEventListener("click", showStory);
    }
  }
  window.addEventListener("message", messageHandler);
}

如果你还有probs,你可以附上整个代码,这样我就可以看到你做了什么,我会帮你一把。

答案 1 :(得分:0)

非常感谢你的帮助。

code title.href=itemLinkcode showUrl(event.currentTarget.href)正是我所需要的。

为了完整性,这里是完整的代码,

    <script id="iframe_script">


    function reportHeight() {
      var msg = JSON.stringify({type:"size", size:document.body.offsetHeight});
      parent.postMessage(msg, "*");
    }

    function frameLoaded() {
      var links = document.getElementsByTagName("A");
      for (i = 0; i < links.length; i++) {
        var class = links[i].className;
        if (class != "item_title" && class != "open_box") {
          links[i].addEventListener("click", showStory);
        }
      }
      window.addEventListener("message", messageHandler);
    }

    function showStory(event) {
      var href = event.currentTarget.href;
      parent.postMessage(JSON.stringify({type:"show", url:href}), "*");
      event.preventDefault();
    }

    function messageHandler(event) {
      reportHeight();
    }

    </script>

<script>

// Feed URL.
var feedUrl = 'http://localhost/newsfeed.xml';

// The XMLHttpRequest object that tries to load and parse the feed.
var req;

function main() {
  req = new XMLHttpRequest();
  req.onload = handleResponse;
  req.onerror = handleError;
  req.open("GET", feedUrl, true);
  req.send(null);
}

// Handles feed parsing errors.
function handleFeedParsingFailed(error) {
  var feed = document.getElementById("feed");
  feed.className = "error";
  feed.innerText = "Error: " + error;
}

// Handles errors during the XMLHttpRequest.
function handleError() {
  handleFeedParsingFailed('Failed to fetch RSS feed.');
}

// Handles parsing the feed data we got back from XMLHttpRequest.
function handleResponse() {
  var doc = req.responseXML;
  if (!doc) {
    handleFeedParsingFailed("Not a valid feed.");
    return;
  }
  buildPreview(doc);
}

// The maximum number of feed items to show in the preview.
var maxFeedItems = 10;

// Where the more stories link should navigate to.
var moreStoriesUrl;

function buildPreview(doc) {
  // Get the link to the feed source.
  var link = doc.getElementsByTagName("link");
  var parentTag = link[0].parentNode.tagName;

  if (parentTag != "item" && parentTag != "entry") {
    moreStoriesUrl = link[0].textContent;
  }

  // Setup the title image.
  var images = doc.getElementsByTagName("image");
  var titleImg;

  if (images.length != 0) {
    var urls = images[0].getElementsByTagName("url");
    if (urls.length != 0) {
      titleImg = urls[0].textContent;
    }
  }
  var img = document.getElementById("title");

  // Listen for mouse and key events
  if (titleImg) {
    img.src = titleImg;
    if (moreStoriesUrl) {
      document.getElementById("title_a").addEventListener("click",moreStories);
      document.getElementById("title_a").addEventListener("keydown", 
                                         function(event) {
                                           if (event.keyCode == 13) {
                                             moreStories(event);
                                           }});
    }
  } else {
    img.style.display = "none";
  }



  // Construct the iframe's HTML.
  var iframe_src = "<!doctype html><html><head><script>" +
                   document.getElementById("iframe_script").textContent + "<" +
                   "/script></head><body onload='frameLoaded();' " +
                   "style='padding:0px;margin:0px;'>";

  var feed = document.getElementById("feed");
  // Set ARIA role indicating the feed element has a tree structure
  feed.setAttribute("role", "tree");


    var entries = doc.getElementsByTagName('item');

  var count = Math.min(entries.length, maxFeedItems);
  for (var i = 0; i < count; i++) {
    item = entries.item(i);

    // Grab the title for the feed item.
    var itemTitle = item.getElementsByTagName('title')[0];
    if (itemTitle) {
      itemTitle = itemTitle.textContent;
    } else {
      itemTitle = "Unknown title";
    }

    // Grab the link for the feed item.
    var itemLink = item.getElementsByTagName('link')[0];
   if (itemLink) {
      itemLink = itemLink.textContent;
    } else {
      itemLink = "Unknown link"; 
    }


    var item = document.createElement("div");

    var title = document.createElement("a");
    title.innerText = itemTitle; //display title in iframe
    title.href=itemLink;
    title.addEventListener("click", titleLink);

    item.appendChild(title);   
    feed.appendChild(item);

  }

  if (moreStoriesUrl) {
    var more = document.createElement("a");
    more.className = "more";
    more.innerText = "***Site Main Page*** \u00BB";
    more.tabIndex = 0;
    more.addEventListener("click", moreStories);
    more.addEventListener("keydown", function(event) {
                                       if (event.keyCode == 13) {
                                         moreStories(event);
                                       }});
    feed.appendChild(more);
  }
 } 

// -------------------------------------------------------------------

// Show |url| in a new tab.
function showUrl(url) {
  // Only allow http and https URLs.
  if (url.indexOf("http:") != 0 && url.indexOf("https:") != 0) {
    return;
  }
  chrome.tabs.create({url: url});
}


// -------------------------------------------------------------------

function moreStories(event) {
  showUrl(moreStoriesUrl);
}

function titleLink(event) {
  showUrl(event.currentTarget.href);
}

function keyHandlerShowDesc(event) {
// Display content under heading when spacebar or right-arrow pressed
// Hide content when spacebar pressed again or left-arrow pressed
// Move to next heading when down-arrow pressed
// Move to previous heading when up-arrow pressed
  if (event.keyCode == 32) {
    showDesc(event);
  } else if ((this.parentNode.className == "item opened") &&
           (event.keyCode == 37)) {
    showDesc(event);
  } else if ((this.parentNode.className == "item") && (event.keyCode == 39)) {
    showDesc(event);
  } else if (event.keyCode == 40) {
    if (this.parentNode.nextSibling) {
      this.parentNode.nextSibling.children[1].focus();
    }
  } else if (event.keyCode == 38) {
    if (this.parentNode.previousSibling) {
      this.parentNode.previousSibling.children[1].focus();
    }
  }
}

function showDesc(event) {
  var item = event.currentTarget.parentNode;
  var items = document.getElementsByClassName("item");
  for (var i = 0; i < items.length; i++) {
    var iframe = items[i].getElementsByClassName("item_desc")[0];
    if (items[i] == item && items[i].className == "item") {
      items[i].className = "item opened";
      iframe.contentWindow.postMessage("reportHeight", "*");
      // Set the ARIA state indicating the tree item is currently expanded.
      items[i].getElementsByClassName("item_title")[0].
        setAttribute("aria-expanded", "true");
      iframe.tabIndex = 0;
    } else {
      items[i].className = "item";
      iframe.style.height = "0px";
      // Set the ARIA state indicating the tree item is currently collapsed.
      items[i].getElementsByClassName("item_title")[0].
        setAttribute("aria-expanded", "false");
      iframe.tabIndex = -1;
    }
  }
}

function iframeMessageHandler(e) {
  // Only listen to messages from one of our own iframes.
  var iframes = document.getElementsByTagName("IFRAME");
  for (var i = 0; i < iframes.length; i++) {
    if (iframes[i].contentWindow == e.source) {
      var msg = JSON.parse(e.data);
      if (msg) {
        if (msg.type == "size") {
          iframes[i].style.height = msg.size + "px";
        } 
    else if (msg.type == "show") {
          var url = msg.url;
          if (url.indexOf("http://localhost/index.html") == 0) {
            // If the URL is a redirect URL, strip of the destination and go to
            // that directly.  This is necessary because the Google news
            // redirector blocks use of the redirects in this case.
            var index = url.indexOf("&url=");
            if (index >= 0) {
              url = url.substring(index + 5);
              index = url.indexOf("&");
              if (index >= 0)
                url = url.substring(0, index);
            }
          }
          showUrl(url);
        }
      }
      return;
    }
  }
}

window.addEventListener("message", iframeMessageHandler);
</script>

再次感谢您的帮助。

-Mike