【发布时间】:2019-08-11 14:12:17
【问题描述】:
感谢 Hellion 的帮助,解决了!
代码如下:
// ==UserScript==
// @name Facebook Comment Moderation Links
// @description Appends story titles to Facebook Comment Moderation "Visit Website" links
// @include http*://developers.facebook.com/tools/*
// ==/UserScript==
var allLinks, thisLink, expr, pageTitle, myURL, myPage, pageContent, title;
// grabbing URLs
function fetchPage(myPage, targetLink) {
GM_xmlhttpRequest({
method: 'GET',
url: myPage,
onload: function(response){
// get the HTML content of the page
pageContent = response.responseText;
// use regex to extract its h1 tag
pageTitle = pageContent.match(/<h1.*?>(.*?)<\/h1>/g)[0];
// strip html tags from the result
pageTitle = pageTitle.replace(/<.*?>/g, '');
// append headline to Visit Website link
title = document.createElement('div');
title.style.backgroundColor = "yellow";
title.style.color = "#000";
title.appendChild(document.createTextNode(pageTitle));
targetLink.parentNode.insertBefore(title, targetLink.nextSibling);
}
});
}
function processLinks() {
// define which links to look for
expr = "//a[contains (string(), 'Visit Website')]";
allLinks = document.evaluate(
expr,
document,
null,
XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE,
null);
// loop through the links
for (var i = 0; i < allLinks.snapshotLength; i++) {
thisLink = allLinks.snapshotItem(i);
myURL = thisLink.getAttribute('href');
// follow Visit Website link and attach corresponding headline
fetchPage(myURL, thisLink);
}
}
// get the ball rolling
processLinks();
--- 下面的早期内容 ---
我正在尝试制作一个 Greasemonkey 脚本,该脚本从一组链接中的每一个中获取 URL,并将页面的 h1 标记的内容附加到链接的末尾。
到目前为止,我可以让它显示 URL 本身,这不需要页面请求,但不需要页面的 h1 标记内容。
我从本网站上的其他问题了解到 GM_xmlhttpRequest 是异步的,我很确定这至少是部分原因。但是我找不到这个特定问题的解决方案。
下面是我到目前为止的代码。它适用于 Facebook 的网站评论审核工具——在版主视图中,每条评论都有一个链接“访问网站”,可将您带到评论所在的文章。
正如现在所写的那样,它将附加 HTTP 状态代码,而不是页面标题,然后是每个“访问网站”链接的 URL。状态码部分只是一个占位符。我计划添加HTML解析等,以便稍后获取h1标签。
现在我只是想让 GM_xmlhttpRequest 和内容插入匹配。
任何帮助解决这个问题将不胜感激。谢谢!
var allLinks, thisLink, expr, pageTitle, myURL, pageContent, title;
// define which links to process
expr = "//a[contains (string(), 'Visit Website')]";
allLinks = document.evaluate(
expr,
document,
null,
XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE,
null);
// cycle through links
for (var i = 0; i < allLinks.snapshotLength; i++) {
thisLink = allLinks.snapshotItem(i);
myURL = thisLink.getAttribute('href');
GM_xmlhttpRequest({
method: 'GET',
url: myURL,
onload: function(responseDetails){
pageTitle = responseDetails.status;
}
});
// append info to end of each link
title = document.createElement('div');
title.style.backgroundColor = "yellow";
title.style.color = "#000";
title.appendChild(document.createTextNode(
' [' + pageTitle + ' - ' + thisLink.getAttribute('href') + ']'));
thisLink.parentNode.insertBefore(title, thisLink.nextSibling);
}
【问题讨论】: