Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to supply a baseURI when using DOMParser.parseFromString?

Tags:

javascript

I am using DOMParser to parse a document that contains relative URLs for things like the action property of a form. Because the baseURI of the document created by DOMParser is null accessing the action property yields a blank string. I can get around this by using getAttribute but if it is possible to specify a baseURI when using DOMParser that would be ideal.

like image 509
Chris_F Avatar asked Dec 08 '16 22:12

Chris_F


1 Answers

Rather than injecting a <base> in the HTML before parsing, have you considered doing something similar after parsing?

function parse(baseUri, htmlStr) {
    var doc = (new DOMParser).parseFromString(htmlStr, 'text/html');
    var base = doc.createElement('base');
    base.href = baseUri;
    doc.head.appendChild(base);
    return doc;
}

var parsedDoc = parse('http://example.com', '<form action="/index.html"></form>');

console.log(

    parsedDoc.querySelector('form').action

)
like image 156
customcommander Avatar answered Oct 19 '22 04:10

customcommander