iframeTemplateFn.js 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. let templateFn = (url) => {
  2. return `
  3. <!DOCTYPE html>
  4. <html lang="en">
  5. <head>
  6. <meta charset="UTF-8">
  7. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  8. <title>Webview Preview</title>
  9. <style>
  10. body {
  11. margin: 0;
  12. padding: 0;
  13. font-family: Arial, sans-serif;
  14. display: flex;
  15. flex-direction: column;
  16. height: 100vh;
  17. align-items: center;
  18. justify-content: flex-start;
  19. padding-top: 10px;
  20. }
  21. #command-line {
  22. padding: 10px;
  23. font-size: 16px;
  24. width: 80%;
  25. max-width: 600px;
  26. border: 1px solid #ccc;
  27. border-radius: 4px;
  28. margin-bottom: 10px;
  29. }
  30. #refresh-button {
  31. padding: 10px 20px;
  32. font-size: 16px;
  33. background-color: #4CAF50;
  34. color: white;
  35. border: none;
  36. border-radius: 4px;
  37. cursor: pointer;
  38. margin-bottom: 10px;
  39. }
  40. #refresh-button:hover {
  41. background-color: #45a049;
  42. }
  43. iframe {
  44. flex-grow: 1;
  45. width: 100%;
  46. height: 100%;
  47. border: none;
  48. }
  49. </style>
  50. </head>
  51. <body>
  52. <input id="command-line" type="text" value="${url}" placeholder="Enter URL here" />
  53. <button id="refresh-button">Refresh</button>
  54. <iframe id="iframe" src="${url}" sandbox="allow-scripts allow-same-origin"></iframe>
  55. <script>
  56. const vscode = acquireVsCodeApi();
  57. const commandLine = document.getElementById('command-line');
  58. const refreshButton = document.getElementById('refresh-button');
  59. const iframe = document.getElementById('iframe');
  60. function refreshIframe() {
  61. const newUrl = commandLine.value.trim();
  62. if (newUrl) {
  63. iframe.src = newUrl; // Update iframe directly
  64. vscode.postMessage({ command: 'refreshUrl', url: newUrl }); // Send update message to VSCode extension
  65. }
  66. }
  67. // Refresh on button click
  68. refreshButton.addEventListener('click', refreshIframe);
  69. // Refresh on pressing Enter
  70. commandLine.addEventListener('keypress', (event) => {
  71. if (event.key === 'Enter') {
  72. refreshIframe();
  73. }
  74. });
  75. // Update input field when the iframe's URL changes (only works for same-origin pages)
  76. iframe.addEventListener('load', () => {
  77. try {
  78. commandLine.value = iframe.contentWindow.location.href;
  79. } catch (error) {
  80. console.warn('Cannot access iframe URL due to cross-origin restrictions.');
  81. }
  82. });
  83. </script>
  84. </body>
  85. </html>
  86. `
  87. };
  88. module.exports = templateFn;