Using Javascript to click on a given button AND have it open in a new window

≯℡__Kan透↙ 提交于 2019-12-11 11:51:32

问题


When this page loads, I want to simulate automatically clicking the send me this thing button whilst having it open in a new window (or new tab)

  • There will only ever be one send me this thing button on any page like that

What for?

This is for Greasekit on Fluid.app, which is similar to Greasemonkey.


回答1:


That Button is a link and that page uses jQuery. So you can get the button like:

var buyItBtn = $("a:contains('Send me this thing')");

Then modify the link to open in a new tab/window.
Then click the link.

The code is:

//-- Note  that :contains() is case-sensitive.
var buyItBtn = $("a:contains('Send me this thing')");
buyItBtn.attr ("target", "_blank");
buyItBtn[0].click ();

BUT, beware that modern popup blockers will block this, I don't know about the webkit embedded in your version of Fluid. Tell your popup blocker to allow these particular popups.

Also, because this is Greasekit, you need to inject the above code, so the complete userscript will be something like:

// ==UserScript==
// @name        _Amazon-like store, buy things in a new window
// @include     https://dl.dropboxusercontent.com/u/5546881/*
// @grant       GM_addStyle
// ==/UserScript==
/*- The @grant directive is needed to work around a design change
    introduced in GM 1.0.   It restores the sandbox.
*/
function GM_main () {
    //-- Note  that :contains() is case-sensitive.
    var buyItBtn = $("a:contains('Send me this thing')");
    buyItBtn.attr ("target", "_blank");
    buyItBtn[0].click ();
}

addJS_Node (null, null, GM_main);

function addJS_Node (text, s_URL, funcToRun, runOnLoad) {
    var D                                   = document;
    var scriptNode                          = D.createElement ('script');
    if (runOnLoad) {
        scriptNode.addEventListener ("load", runOnLoad, false);
    }
    scriptNode.type                         = "text/javascript";
    if (text)       scriptNode.textContent  = text;
    if (s_URL)      scriptNode.src          = s_URL;
    if (funcToRun)  scriptNode.textContent  = '(' + funcToRun.toString() + ')()';

    var targ = D.getElementsByTagName ('head')[0] || D.body || D.documentElement;
    targ.appendChild (scriptNode);
}


来源:https://stackoverflow.com/questions/19579613/using-javascript-to-click-on-a-given-button-and-have-it-open-in-a-new-window

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!