Я получаю .push это не функция? Зачем? Скрипт Greasemonkey - PullRequest
0 голосов
/ 30 августа 2018

Я написал скрипт greasmonkey ниже, кто-нибудь может сказать мне, почему возникает эта ошибка? Это работает, когда я удаляю обработчик событий document.add, но я хочу, чтобы он работал с этим.

Этот сценарий сопоставляет входные данные, которые пользователь вводит в поле, а затем сопоставляет их с продуктом, имеющим соответствующий тег, который в данном случае является аксессуарами для волос, если входные данные вводятся в поле, а затем идентификатор продукта. match затем вызовет всплывающее сообщение, которое позже было сохранено в переменной в скрипте.

(Ошибка - Uncaught TypeError: limitedItems.push не является функцией)

Любая помощь с этим была бы полезна, чтобы заставить ее работать, я просмотрел много статей, и ни одна из которых не помогает на данный момент.

// ==UserScript==
// @name        Age Verification
// @namespace   http://tampermonkey.net/
// @include     /https?:\/\/stackoverflow\.com\/*/
// @require     https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js
// @require     https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js
// @resource    buttonCSS https://raw.githubusercontent.com/necolas/css3-github-buttons/master/gh-buttons.css
// @resource    bootstrapCSS https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css
// @resource    githubButtonIconSet https://raw.githubusercontent.com/necolas/css3-github-buttons/master/gh-icons.png
// @grant       GM_addStyle
// @grant       GM_getResourceText
// @grant       GM_getResourceURL
// @grant       GM_xmlhttpRequest
// @grant       GM_log
// ==/UserScript==

(function() {
    'use strict';

    var xmlhttp = new XMLHttpRequest();
    var page = 1;
    var url = "";
    var restrictedItems = [];

    xmlhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            var results = JSON.parse(this.responseText);
            processResults(results);
        }
    };

    getProducts();

    function getProducts(page) {
        url = "/api/products/active/1/page/"+page+"/page_size/200";
        xmlhttp.open("GET", url, true);
        xmlhttp.send();
    }

    function processResults(resultsArray) {
        var out = "";
        var i;
        resultsArray.products.forEach(function(product) {
            if (product.tags.includes('Hair Accessories')) {
                // NOTE: This will probably not work with the "Sell Screen 3" script as that adds enhanced functionality for the barcode/SKU that this probably won't detect
                restrictedItems.push(product.sku);
            }
        });

        //console.log(resultsArray);
        //console.log(restrictedProducts);
        if (resultsArray.pagination.page < resultsArray.pagination.pages) {
            page++;
            getProducts(page);
        }
    }


    document.addEventListener("keyup", function(e) {
    restrictedItems = e.target.value;
        console.log(restrictedItems);

        });


document.head.appendChild(cssElement(GM_getResourceURL ("githubButtonIconSet")));
document.head.appendChild(cssElement(GM_getResourceURL ("buttonCSS")));
document.head.appendChild(cssElement(GM_getResourceURL ("bootstrapCSS")));




document.body.onkeyup = function(e){

    if(e.keyCode == 13){
        gettingdata();

    }
}

function cssElement(url) {
  var link = document.createElement("link");
  link.href = url;
  link.rel="stylesheet";
  link.type="text/css";
  return link;
}



function gettingdata() {

    var scannedItem = document.getElementsByClassName('vd-input')[0].value;
    console.log(restrictedItems);
    console.log(scannedItem);


    for (var i = 0; i < scannedItem.length; i++) {
    if (restrictedItems[i] == scannedItem) {

        bringUpModal();
        return true;
         }

    }
    return false;

}

function bringUpModal () {
    'use strict';
    var modalHtml = `
<!-- Modal -->
<style>
.body{-webkit-filter: blur(5px) grayscale(90%);}
</style>
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true" data-backdrop="static" data-keyboard="false" >
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header" style="background-color:#3A4953;">
        <h4 class="modal-title" id="myModalLabel" style="color:white; text-transform: uppercase;" ><b>Age Restricted Item</b></h4>
      </div>
      <div class="modal-body">
        <p style="font-weight:700;"> Have you checked the age of the Person? Only a Valid Passport or Driving Licence may be accecpted for ID </p>
<br/>
<br/>
<center>
        <img src="https://www.speedy-delivery.ca/uploads/369x0_170x0/badge-ID25.png" >
</center>
<br/>
<br/>
       <ul>
          <li><b>Liqueur</b> - 16 Years Old </li>
          <li><b>Alcohol</b> - 18 Years Old </li>
          <li><b>Lighter Refills</b> - 18 Years Old </li>
          <li><b>Knives and Razors</b> - 18 Years Old </li>
          <li><b>Medicines (Pain Relief)</b> - 2 Packs Only for <b>all ages per transaction</b> </li>
        </ul>

           <p style="color:red; font-weight:700;"> If the person is younger than the age allowed for the item then please remove that item from the checkout process! </p>

      </div>
      <div class="modal-footer">

        <button type="button" class="btn btn-default" data-dismiss="modal" style="color:red; background-color:white; border:solid red;"><b>Failed Age ID Verification</b></button>
        <button type="button" class="btn btn-primary" data-dismiss="modal" style="background-color:#3A4953; color:white;">Approve Age ID Verification</button>
      </div>
    </div>
  </div>
</div>
`;

    $("body").prepend(modalHtml);
    $('#myModal').modal('show');
}
})();

1 Ответ

0 голосов
/ 30 августа 2018
restrictedItems = e.target.value;

Вы перезаписали массив строкой. Строки не имеют метода push.

...