Shadow DOM: Is it possible to encapsulate JS?

I am trying to find a way to encapsulate Javascript without using iframes. Ideally, I would like to upload external HTML components (widgets) to the parent page without the two-step loading process that comes with iframes (the host page is loaded first, and only then iframe content is loaded).

Is it possible to do this with some new web component technologies - shadow DOM / templates / import? I managed to get close to adding HTML to the shadow DOM and encapsulating CSS, but I couldn’t confirm whether I could get a separate document to execute the javascript component.

+4
source share
3 answers

The web components used through HTML import encapsulate both the shadow HTML code and the associated script.

To narrow down the terminology, consider that we have a core-ajax polymer component . Here is the code . As you can see, it does not contain any HTML markup at all, enclosing only a script.

After importing on the host web page:

<link 
  rel="import"
  href="https://www.polymer-project.org/components/core-ajax/core-ajax.html"> 

this component provides the ability to make AJAX calls without javascript encoding:

<core-ajax
  auto
  url="http://gdata.youtube.com/feeds/api/videos/"
  params='{"alt":"json", "q":"chrome"}'
  handleAs="json"
  response='{{response}}'
</core-ajax>

( auto ) URL- response. :

  - response='{{response}}'
  + on-core-response="{{handleResponse}}"

handleResponse javascript .

UPD. , DOM, w3c. , , " ".

+3

dom, javascript: https://benfrain.com/sandbox-local-htmlcss-code-snippets-inside-iframe-style-guidespattern-libraries/

iframe node css javascript:

var newIframe = document.createElement('iframe')
newIframe.contentWindow.document.open('text/html', 'replace')
var content = '<!DOCTYPE html><html><head>'+CSS+'</head><body>'+HTML+JS+'</body></html>'
newIframe.contentWindow.document.write(content)
newIframe.contentWindow.document.close()

javascript , , document.domain - , iframe . . iframe postmessage.

, iframe , -iframe- .

, , .

0

, <style> <script> ( , Shadow DOM):

// Create the shadow DOM
var shadow = document.querySelector('#testOutput').createShadowRoot();

// Get the template fragment and add it to the shadow DOM
shadow.appendChild(document.querySelector('#testTemplate').content);
<template id="testTemplate">
  <script>
    alert('Hello from the component');
  </script>
</template>

<div id="testOutput">shadow</div>
Hide result

Shadow DOM.

, XSS.

0

All Articles