samrum / vite-plugin-web-extension

A vite plugin for generating cross browser platform, ES module based web extensions.
MIT License
323 stars 33 forks source link

Appending an iframe in ContentScript causes a Content Security Policy error. #139

Open chengfengfengwang opened 5 months ago

chengfengfengwang commented 5 months ago
// contentScript.ts
const freamUrl = chrome.runtime.getURL('src/entries/fream/index.html');
const ifream = document.createElement('iframe');
ifream.src = freamUrl;
document.body.appendChild(ifream)

The above code cause CSP error:

image
keyding commented 4 months ago

Hi, @chengfengfengwang

You need to put your html file in the public:

public folder

Here is my sample code:

// contentScript.ts

function renderIframeContent(page: string, render: (iframe: HTMLIFrameElement) => void) {
  const iFrameRoot = document.createElement('div')
  const iFrame = document.createElement('iframe')
  iFrame.src = browser.runtime.getURL(page)

  iFrameRoot.appendChild(iFrame)
  document.body.appendChild(iFrameRoot)

  render(iFrame)
}

renderIframeContent('iframe/index.html', (iframe) => {
  Object.assign(iframe.style, {
    position: 'fixed',
    top: '0',
    right: '0',
    bottom: '0',
    left: '0',
    border: '0',
    zIndex: '9999999',
    overflow: 'visible',
  })
})

I hope this helps!