简体   繁体   English

检索没有名称或ID的元素

[英]Retrieving element with no name or id

I am trying to write some code to accomplish something very simple. 我正在尝试编写一些代码来完成一些非常简单的事情。 I have never worked with a PayPal button before, which is causing some difficulty. 我以前从未使用过PayPal按钮,这引起了一些麻烦。

I have been able to simulate a button click before, using document.getElementById or document.getElementsByName(), however, the form I am trying to submit above does not have a name, or an id, so I do not know how to refer to it in my code. 我之前可以使用document.getElementById或document.getElementsByName()模拟一次按钮单击,但是,我上面试图提交的表单没有名称或ID,所以我不知道如何引用在我的代码中。

I am trying to write a short chrome extension using Javascript that will find the paypal form/button on the page (that I do not own or have control over), and submit it without me having to click it. 我正在尝试使用Javascript编写一个简短的chrome扩展程序,该扩展程序将在页面上找到贝宝表单/按钮(我不拥有或无法控制),然后提交它而无需点击它。 Any guidance/links would be much appreciated. 任何指导/链接将不胜感激。

Looks like your button has a name, so you can use .getElementsByName() 看起来您的按钮有一个名称,因此您可以使用.getElementsByName()

var btn = document.getElementsByname('submit')[0]

If you have access to jQuery or you can add jQuery to your project then 如果您有权使用jQuery,或者可以将jQuery添加到您的项目中,那么

var btn = jQuery('input[name="submit"]')

This would be MUCH easier with jQuery, but with native js, you could do: 使用jQuery会更容易,但是使用本机js,您可以执行以下操作:

function getPaypalForms()
{
  var matchingElements = [];
  var allForms = document.getElementsByTagName('form');
  for (var i = 0; i < allForms.length; i++)
  {
    if (allForms[i].getAttribute('action') == 'https://www.paypal.com/cgi-bin/webscr')
    {
      // Element exists with attribute. Add to array.
      matchingElements.push(allElements[i]);
    }
  }
  return matchingElements;
}

There are many ways to edit this function above to suit your purposes even better. 您可以通过多种方法来编辑此功能,以更好地满足您的目的。 You could edit it to collect just the submit buttons from these forms, or refactor it to accept a string to match an attr, and value. 您可以对其进行编辑以仅从这些表单中收集提交按钮,或对其进行重构以接受与attr和value匹配的字符串。 However, like I said, this would be much easier using jquery: 但是,就像我说的那样,使用jquery会容易得多:

$('form[action="https://www.paypal.com/cgi-bin/webscr"]');

Based on your update, first off: don't do this, unless you're trying to swindle people out of money. 根据您的更新,首先:不要这样做,除非您试图用钱骗人。 In which case, don't do this =) (I'm not a lawyer, but I'm pretty sure paypal can go "well you didn't click the button, you automated it. And now someone's site made you spend $500 that you didn't want to. tough"). 在这种情况下,请勿执行此操作=)(我不是律师,但我很确定贝宝可以继续前进“好吧,您没有单击按钮,而是对其进行了自动化。现在有人在您的网站上花费了您500美元不想。强硬”)。 That said: document.getElementsByTagName("form"), then filter on getAttribute("action"). 也就是说:document.getElementsByTagName(“ form”),然后对getAttribute(“ action”)进行过滤。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM