Can a Shadow DOM secure my elements?

2019-01-17 04:21发布

问题:

Goal: an encapculated widget

Suppose I'm the developer of a friends widget for FakeBook™. I provide a widget for website owners that adds a personalized message like this to their pages:

Your friends Michael, Anna and Shirley love this webpage!

First approach: script that creates span

Naively, I create a script which places this information in a span on the website. However, the owners of ExampleSite can now access the names of your friends by simple DOM operations!
That's a big privacy / security issue.

Second approach: an iframe

I don't want ExampleSite to have access to their friends' names. So instead, I let website owners add the widget with an iframe:

<iframe src="http://fakebook.com/friends?page=http%3A%2F%2Fexample.org%2F"></iframe>

This works, because the owners of ExampleSite cannot scrape the contents of the iframe. However, this whole iframe thing is rather ugly, because it does not integrate into the styling of the website, while a span does.

Desired approach: Shadow DOM

When reading about Shadow Dom yesterday, I wondered whether that could be a solution to both issues. It would allow me to have a script that creates a span the original website cannot access:

var host = document.querySelector('#friends');
var root = host.webkitCreateShadowRoot();
root.textContent = 'Your friends Michael, Anna and Shirley love this webpage!';


However, does a Shadow DOM hide its contents from the surrounding page?
The assumption here is that nobody except my script can access root, but is that correct?

The Shadow DOM spec after all says that it offers functional encapsulation, but I actually want trust encapsulation. And while the Component Model Use Cases actually list this use case, I'm not sure whether Shadow DOM realizes the nesessary confinement property.

回答1:

It does not, but it's in the works: https://www.w3.org/Bugs/Public/show_bug.cgi?id=20144

The encapsulation of trust will involve creating a new scripting context for each shadow tree, which is overkill for most scenarios. However, as the bug says, we'll add a flag (details TBD) that would allow this.