简体   繁体   中英

Calling a javascript function in another javascript file without include

I have a question about javascript function flow. I am building a chrome extension where one javascript file creates a popup window using window.open . Based on the button selected in the popup, a variable is set and a function in the original javascript function should be called. But, it doesn't recognize that function from the original javascript file. I don't want to include file1 in file2's header, because other functions that I don't need would be called within file2. How do I handle this case?

A snippet of my code is the following:

in default_popup.html

<html
<head>
     <script type="text/javascript" src="login.js"></script>
</head>
</html>

in login.js

function login() {
    if (token === null) {
        var url = chrome.extension.getURL('options.html');
        window.open(url);
    }
    else {....}
function auth(url) {
............
}
//other functions here

in options.html

 <html>
 <head>
     <script type="text/javascript" src="redirect.js"></script>
 </head>
 <body>
    <button id="button1">Option1</button>
    <button id="button2">Option2</button>
  </body>
  </html>

in redirect.js

 var url;
 document.getElementById('button1').onclick = function() {
    url = 'url_one.com';
    auth(url)
 }
 document.getElementById('button2').onclick = function() {
    url = 'url_two.com';
    auth(url);
 }

Create a different JS file and you can call it common.js.

Transfer all the functions that needs to be accessed by both files there.

It is possible passing a function in the window reference, however chrome security setting may interfere that with local files because of the "same origin security principal", it works in other browsers on local, not sure in server pages and extension, so worth the test, follow the example:

html1:

<html>
    <head>
        <script type="text/javascript">
            function test(){
                var windowRef = window.open('test2.html');
                windowRef['auth'] = function(){windowRef.document.write('property transferred')}
            }//here you'll reference your auth function.
        </script>
    </head>
    <body>
    <input type="button" value="test" onclick="test()" >
    </body>
</html>

html2:

<html>
    <head>
        <script type="text/javascript">
            window['auth']() //the function to call, window.auth() should work too.
        </script>
    </head>
    <body>
    new window
    </body>
</html>

The output will be a new window with "property transferred" in it.

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