3

Inside a web worker, I have an html string like:

"<div id='foo'>  <img src='bar'></img>  <ul id='baz'></ul>  </div>"

Is there any library I can import to easily access id and src attributes of the different tags ? Is regex the only way inside a worker ?

Rob W
  • 341,306
  • 83
  • 791
  • 678
Running Turtle
  • 12,360
  • 20
  • 55
  • 73
  • Some XML parsers might help here if you have XHTML. See http://stackoverflow.com/questions/9540218/a-javascript-parser-for-dom – pd40 Nov 26 '12 at 00:39
  • 1
    @pd40 Inside Web Workers, the DOM API is not supported. – Rob W Nov 26 '12 at 09:27

1 Answers1

2

There are two ways to solve this problem efficiently:

Regex

With the risk of getting false positives, you can use something like:

var pattern = /<img [^>]*?src=(["'])((?:[^"']+|(?!\1)["'])*)(\1)/i;
var match = string.match(pattern);
var src = match ? match[2] : '';

Built-in parser & messaging

If getting the HTML right is a critical requirement, just let the browser parse the HTML, by passing the string to the caller. Here's a full example:

Caller:

var worker = new Worker('worker.js');
worker.addEventListener('message', function(e) {
    if (!e.data) return;
    if (e.data.method === 'getsrc') {
        // Unlike document.createElement, etc, the following method does not 
        //  load the image when the HTML is parsed
        var doc = document.implementation.createHTMLDocument('');
        doc.body.innerHTML = e.data.data;
        var images = doc.getElementsByTagName('img');
        var result = [];
        for (var i=0; i<images.length; i++) {
            result.push(images[i].getAttribute('src'));
        }
        worker.postMessage({
            messageID: e.data.messageID,
            result: result
        });
    } else if (e.data.method === 'debug') {
        console.log(e.data.data);
    }
});

worker.js

// A simple generic messaging API
var callbacks = {};
var lastMessageID = 0;
addEventListener('message', function(e) {
   if (callbacks[e.data.messageID]) {
       callbacks[e.data.messageID](e.data.result);
   }
});
function sendRequest(method, data, callback) {
    var messageID = ++lastMessageID;
    if (callback) callbacks[messageID] = callback;
    postMessage({
        method: method,
        data: data,
        messageID: messageID
    });
}

// Example:
sendRequest('getsrc',
    '<img src="foo.png">' + 
    "<img src='bar.png'>" + 
    '<textarea><img src="should.not.be.visible"></textarea>',
    function(result) {
        sendRequest('debug', 'Received: ' + result.join(', '));
    }
);
Rob W
  • 341,306
  • 83
  • 791
  • 678