简体   繁体   中英

How to run vanilla javascript after react loads?

I want to create a script and using react as the playground. Long story short the script will be a standalone chrome extension that will be used to manipulate websites (those react powered also).

So inside the react project, in public/index.html I have this:

    ....
    <noscript>You need to enable JavaScript to run this app.</noscript>
    <div id="root"></div>

    <script src="./extension/main.js"></script>
  </body>
</html>

And inside main.js I want to wait for react to load the data into #root (as it does) and then I want to start my own code

document.addEventListener("DOMContentLoaded", function() {
  if(window.localStorage.getItem('highlights')){
    makeSelection(JSON.parse(window.localStorage.getItem('highlights')))
  }
})

But that's not working.

(Not, I can't use react hooks, this will be totally independent of react, I just want to make sure when it runs in a react site it works)

您可以启动一些 timeOut 来检查 #root 是否有空的 innerHTML,以及它是否没有运行您的代码

I would do it like this:

first, in extension/main.js file I will wrap all my code in global function let's call it on onAppDidMount

window.onAppDidMount = function(){
    ... // all main.js code here
}

and in the root component, I will call this global function after root component mounted

class App extends React.Component{

    componentDidMount(){
         window.onAppDidMount();
    }
    ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM