此脚本有助于在线商店的结帐流程。一切正常,除了需要刷新页面以使程序最初运行。
不知道是不是缓存的问题,因为在之前看过的其他产品上也有效果。我还尝试修改 @run-at
但无济于事。我使用的是 Scriptish 扩展,它是一个独立的 .js
文件。
// ==UserScript==
// @id proper-id
// @name proper-name
// @version 1.0
// @namespace
// @description
// @include proper-url-here
// @include about:blank
// @run-at window-load
// ==/UserScript==
for (var i=0; i<document.getElementsByName("skuAndSize")[0].length; i++){
if(document.getElementsByName("skuAndSize")[0].options[i].text == 11) {
document.getElementsByName("skuAndSize")[0].selectedIndex = i;
}
}
document.getElementsByClassName("button-container add-to-cart")[0].click();
为什么这个用户脚本只在刷新时运行?
最佳答案
这是通过 AJAX 更改内容的页面的典型问题。
@run-at
没有效果,因为目标内容在窗口 load
事件之后很长时间才加载。而且,"new"页面实际上是通过 AJAX 完全重写的——至少在您刷新页面之前是这样。
将脚本更改为 @run-at document-end
(或省略该行)然后,根据目标页面和您的使用方式,它可能足以触发hashchange
如 "I have to refresh the page for my Greasemonkey script to run?" 所示或如 this other answer 所示.
转到工具是waitForKeyElements
More info , 然而。您的脚本可能很简单:
// ==UserScript==
// @name _YOUR_SCRIPT_NAME
// @include http://YOUR_SERVER.COM/YOUR_PATH/*
// @require http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js
// @require https://gist.github.com/raw/2625891/waitForKeyElements.js
// ==/UserScript==
waitForKeyElements ("[name='skuAndSize']", setSizeIndex);
waitForKeyElements (".button-container.add-to-cart", clickAddToCart);
function setSizeIndex (jNode) {
var node = jNode[0];
for (var J = node.options.length - 1; J >= 0; --J) {
if (node.options[J].text == "11") {
node.selectedIndex = J;
break;
}
}
}
function clickAddToCart (jNode) {
var clickEvent = document.createEvent ('MouseEvents');
clickEvent.initEvent ('click', true, true);
jNode[0].dispatchEvent (clickEvent);
}
另见 "Choosing and activating the right controls on an AJAX-driven site" .
关于javascript - Scriptish 脚本需要刷新页面才能运行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17385145/