Импорт require.js в расширение Chrome - PullRequest
0 голосов
/ 06 декабря 2018

Я создаю расширение и начал с руководства для разработчиков Chrome.Я хочу очистить веб-страницу и получить всплывающее окно, если цена достигнет значения X.

Я заказываю, чтобы заставить это работать, мне нужно импортировать "cheerio".Я видел много вопросов, похожих на этот, скачал require.js в папку lib, включенную в манифест ... но я не могу понять обходной путь:

Это мой HTML:

<!DOCTYPE html>
<html>
  <head>
    <style>
      button {
        height: 30px;
        width: 30px;
        outline: none;
        margin: 10px;
      }
    </style>
  </head>
  <body>
    <div id="buttonDiv">
    </div>
  </body>
  <script src="options.js"></script>
</html>

Это мой манифест:

{
    "name": "PriceTracker",
    "version": "1.0",
    "description": "Track your wishlist!",
    "permissions": ["activeTab", "declarativeContent", "storage"],
    "background": {
        "scripts": ["background.js","lib/require.js"],
        "persistent": false
      },
      "options_page": "options.html",
      "page_action": {
        "default_popup": "popup.html",
        "default_icon": {
          "16": "images/get_started16.png",
          "32": "images/get_started32.png",
          "48": "images/get_started48.png",
          "128": "images/get_started128.png"
        }
      },
      "icons": {
        "16": "images/get_started16.png",
        "32": "images/get_started32.png",
        "48": "images/get_started48.png",
        "128": "images/get_started128.png"
      },

    "manifest_version": 2
  }

Это background.js:

'use strict';

// tested this and no success
function loadScript(scriptName, callback) {
    var scriptEl = document.createElement('script');
    scriptEl.src = chrome.extension.getURL('lib/' + scriptName + '.js');
    scriptEl.addEventListener('load', callback, false);
    document.head.appendChild(scriptEl);
  }





chrome.runtime.onInstalled.addListener(function() {
  chrome.storage.sync.set({color: '#3aa757'}, function() {
    console.log("The color is green.");
  });

  chrome.declarativeContent.onPageChanged.removeRules(undefined, function() {
    chrome.declarativeContent.onPageChanged.addRules([{
      conditions: [new chrome.declarativeContent.PageStateMatcher({
        pageUrl: {hostEquals: 'developer.chrome.com'},
      })
      ],
          actions: [new chrome.declarativeContent.ShowPageAction()]
    }]);
  });

});

и это options.js:

'use strict';

let page = document.getElementById('buttonDiv');

const kButtonColors = ['#3aa757', '#e8453c', '#f9bb2d', '#4688f1'];

function constructOptions(kButtonColors) {
  for (let item of kButtonColors) {
    let button = document.createElement('button');
    button.style.backgroundColor = item;
    button.addEventListener('click', function () {
      chrome.storage.sync.set({ color: item }, function () {
        console.log('color is ' + item);
      })
    });
    page.appendChild(button);
  }
}
constructOptions(kButtonColors);


function getData(url) {
  loadScript("require");
  let cheerio = require('cheerio'); //<-- this is where I get the non existent "require"
  let jsonframe = require('jsonframe-cheerio');

  let $ = cheerio.load(url);
  jsonframe($); // initializes the plugin

  var frame = { ...... };

  var gamesList = $('.offerDetails.category.row').scrape(frame);
  console.log(gamesList); // Output the data in the terminal
}

getData("URLTOPARSE");

Я получаю знаменитую ошибку "Uncaught ReferenceError: require is notfined" ... Любая идея о том, что я делаю неправильно?

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...