簡體   English   中英

使用 Javascript 將 React 應用程序嵌入為小部件失敗,並在 Firefox 和 Chrome 上顯示不同的消息

[英]Embedding React app as a widget with Javascript is failing with different messages on Firefox and Chrome

按照本網站上的步驟,我可以使用 iframe 在另一個網站上嵌入一個反應應用程序作為小部件:

<html>
  <iframe src="http://localhost:3000"><iframe>
</html>

嵌入 Javascript(第二種方法)失敗,並在 Firefox 上顯示以下錯誤消息:

The script from “http://localhost:3000/static/js/main.dbfc58d6.chunk.js” was loaded even though its MIME type (“text/html”) is not a valid JavaScript MIME type.
SyntaxError: expected expression, got '<'

以下是我嵌入反應應用程序的代碼:

<html lang="en">    
<body><noscript>You need to enable JavaScript to run this app.</noscript>
  <div id="root"></div>
  <script type="text/javascript" src="http://localhost:3000/static/js/main.dbfc58d6.chunk.js"></script>
</body>    
</html>

我可以確認我指定的 js 源是正確的並且正在運行: 在此處輸入圖像描述

在 Chrome 上,警告消息顯示如下:

index.html:1 A cookie associated with a cross-site resource at http://localhost/ was set without the `SameSite` attribute. A future release of Chrome will only deliver cookies with cross-site requests if they are set with `SameSite=None` and `Secure`. You can review cookies in developer tools under Application>Storage>Cookies and see more details at https://www.chromestatus.com/feature/5088147346030592 and https://www.chromestatus.com/feature/5633521622188032.
index.html:10 Cross-Origin Read Blocking (CORB) blocked cross-origin response http://localhost:3000/static/js/main.dbfc58d6.chunk.js with MIME type text/html. See https://www.chromestatus.com/feature/5629709824032768 for more details.

尋求指導以解決此問題。 感謝您的閱讀。

更新:參考@Thai 的回答,我將我的源文件指定為由 react 構建操作生成的文件。 如何指定正確的 js 文件來解決我的問題? 在此處輸入圖像描述

我可以確認我指定的 js 源是正確的並且正在運行

感謝您發布該屏幕截圖,因為這對於找出問題所在至關重要。 與您所說的相反,JS 來源不正確。 您的 JavaScript 源代碼只是一個文本文件,它不能在瀏覽器中自行運行。

這意味着當您查看 JavaScript 源文件時,您應該看到源代碼,而不是工作應用程序。

如果 JavaScript 文件的 URL 正確,您應該會看到 JavaScript 代碼而不是工作應用程序

但是,在您的屏幕截圖中,它顯示了實際應用程序,而不是 JavaScript 源。

瀏覽器截圖

您實際得到的是 HTML 頁面。 當找不到您請求的文件時,您的開發服務器可能會提供此頁面。 所以它將索引頁面作為后備。

下次在確認是否正確的時候,可不可以建議你故意弄錯,然后看看結果有沒有不同?

在幫助下解決了這個問題 - 問題是由於我創建構建的方式造成的。

我們不能使用 CRA 自帶的默認構建工具。 請改用rescripts/cli

  1. 安裝 @rescripts/cli 作為開發依賴項:

npm install @rescripts/cli --save-dev

  1. 更新 package.json “腳本”以使用“腳本”運行:

    "scripts": { "start": "rescripts start", "build": "rescripts build", "test": "rescripts test", "eject": "rescripts eject" },

  2. 構建您的應用程序

npm run buiild

  1. 嵌入應用程序:

    <script src="https://localhost:3000/static/js/bundle.js"></script>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM