Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inside a web worker, how to find html attribute from string?

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 ?

like image 627
Running Turtle Avatar asked Dec 11 '25 07:12

Running Turtle


1 Answers

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(', '));
    }
);
like image 177
Rob W Avatar answered Dec 12 '25 22:12

Rob W