Browserify с расширением chrome: невозможно прочитать свойство "_handle" из неопределенного - PullRequest
0 голосов
/ 29 февраля 2020

Я хочу использовать модуль npm в расширении chrome, поэтому я использую browserify.

manifest.json:

{
    "name": "foo",
    "version": "1.0",
    "description": "foo",
    "permissions": ["tabs", "<all_urls>"],
    "browser_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
}

popup.html:

<!DOCTYPE html>

<html>

  <head>
    <script src='bundle.js'></script>
  </head>

  <body style="width:400px;">
    <div id='message'>Fetching HTML content...</div>
  </body>

</html>

popup.js:

chrome.runtime.onMessage.addListener(function(request, sender) {
    if (request.action == "getSource") {
        // Division-content = message.innerText
        // HTML-fetched = request.source

        // HTML content
        // Indices of nick-names are in indices[]
        var htmlContent = request.source;
        var regex = /nick-name="/gi, result, indices = [];
        while(( result = regex.exec(htmlContent) )) {
            indices.push(result.index);
        }

        // User ID's
        // Nick-names are in names[]
        var names = [];
        var i;
        for (i = 0; i < indices.length; i++) {
            var thisIndex = indices[i]+11; // index of the 1st char in ID
            var thisName = '';
            // Substring: [i+11 → double-quote)
            while (htmlContent[thisIndex] !== '"') {
                thisName = thisName.concat(htmlContent[thisIndex]); // Add current char to name
                thisIndex++; // move to next char
            }
            names.push(thisName);
        }

        // Debug: Check indices
        /*
        var contentI = '';
        var x;
        for (x = 0; x < indices.length; x++) {
            contentI = contentI.concat(indices[x].toString());
            contentI = contentI.concat('\n');
        }
        message.innerText = contentI;
        */

        // Debug: Check Names
        var contentNames = '';
        var y;
        for (y = 0; y < names.length; y++) {
            contentNames = contentNames.concat(names[y]);
            contentNames = contentNames.concat('\n');
        }
        message.innerText = contentNames;

        var nodejieba = require("nodejieba");
        var resultjieba = nodejieba.cut("barbarbar");
        message.innerText = resultjieba;
    }
});

function onWindowLoad() {
    var message = document.querySelector('#message');

    chrome.tabs.executeScript(null, {
        file: "getPagesSource.js" // I don't think this js file is related to this question so I won't post it here
    }, function() {
        // If you try and inject into an extensions page or the webstore/NTP you'll get an error
        if (chrome.runtime.lastError) {
            message.innerText = 'There was an error injecting script : \n' + chrome.runtime.lastError.message;
        }
    });
}

window.onload = onWindowLoad;

Я использую команду browserify popup.js -o bundle.js (на основе примера hello-world от Browserify ) для объединения popup.js и требуемого npm модуля, но браузер возвращает сообщение об ошибке «Ошибка в обработчике события: ошибка типа: невозможно прочитать свойство« _handle »из неопределенного».


bundle.js слишком длинное. Я не буду публиковать это здесь, но проблема в этой строке ...

module.exports = function (blocking) {
  [process.stdout, process.stderr].forEach(function (stream) {
    if (stream._handle && stream.isTTY && typeof stream._handle.setBlocking === 'function') {
      stream._handle.setBlocking(blocking)
    }
  })
...