我正在为GMail创建一个脚本,它要求我复制左侧的各种链接,如收件箱,所有邮件,垃圾邮件和撰写。 我有所有的链接工作,除了撰写。当我点击时,我无法弄清楚会发生什么。你可以在下面找到我的代码。我很感激任何帮助
// ==UserScript==
// @name GMC Test
// @namespace com.pbg
// @description test
// @include http*://mail.google.com*
// ==/UserScript==
//loading function
function tryAgain(tries) {
setTimeout(function() { init(tries++); }, 1000*tries);
}
//gets a node by XPath
function getNodeByXPath(expression, parent) {
var r = parent.evaluate(expression, parent, null, XPathResult.ORDERED_NODE_ITERATOR_TYPE, null);
return ((r != null) ? r.iterateNext() : null);
}
//initialize
function init(tries) {
tries = tries || 0;
if (tries > 3) return; // give up, too many tries
// Locate the canvas_frame iframe
var f = document.getElementById("canvas_frame");
if (f == null) return tryAgain(tries);
// Locate the document
var doc = f.contentWindow.document;
if (doc == null) return tryAgain(tries);
// make sure all the links are loaded
if (getNodeByXPath("//a[contains(@href,'#inbox')]", doc) == null) return tryAgain(tries);
go();
}
function go() {
function fireEvent(xPath,event)//https://developer.mozilla.org/en/DOM/element.dispatchEvent
{
var evt = document.createEvent("MouseEvents");
evt.initMouseEvent(event, true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
var cb = getNodeByXPath(xPath, doc);
var canceled = !cb.dispatchEvent(evt);
GM_log("event canceled = " + canceled);
}
var doc = document.getElementById("canvas_frame").contentWindow.document;
//THE LINE BELOW WORKS
//setTimeout(function(){GM_log("let's click starred!");fireEvent("//a[contains(@href,'#starred')]", "click")}, 5000);
//THIS DOENS'T WORK
setTimeout(function(){GM_log("now let's click compose!");fireEvent("//div[@class='J-Zh-I J-J5-Ji L3')]", "click")}, 5000);
}
window.addEventListener('load', init, false );
答案 0 :(得分:3)
如果您使用较新的AJAX-y样式GMail,您可以将页面的href更改为compose url,如下所示*并让页面的事件处理程序像往常一样触发/处理标签更改:
document.location.href = "#compose";
或者,如果您使用的是基本HTML视图,则可以使用xPath查找撰写邮件锚点并更改document.location.href
以匹配链接指向的任何内容。
我确信可以编写更优雅/更有弹性的xPath,但是现在简单的说明表明它的accesskey属性设置为c,这可能足以区分正确的链接:
var nodesSnapshot = document.evaluate(
'//*[@accesskey="c"]',
document,
null,
XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,
null
);
document.location.href = nodesSnapshot.snapshotItem(0).href;
* nb:两者都经过测试并且在Firebug中工作,但由于在AJAX-y视图/其他因素等中使用了iFrame,可能在Greasemonkey脚本中的工作方式不同