[英]Calling a javascript function in another javascript file without include
我對javascript函數流有疑問。 我正在構建一個chrome擴展程序,其中一個JavaScript文件使用window.open
創建了一個彈出窗口。 根據在彈出窗口中選擇的按鈕,將設置一個變量,並應調用原始javascript函數中的一個函數。 但是,它無法從原始javascript文件中識別該功能。 我不想在文件2的標頭中包含文件1,因為不需要的其他功能將在文件2中調用。 我該如何處理?
我的代碼段如下:
在default_popup.html中
<html
<head>
<script type="text/javascript" src="login.js"></script>
</head>
</html>
在login.js中
function login() {
if (token === null) {
var url = chrome.extension.getURL('options.html');
window.open(url);
}
else {....}
function auth(url) {
............
}
//other functions here
在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>
在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);
}
創建另一個JS文件,您可以將其稱為common.js。
將兩個文件都需要訪問的所有功能都轉移到那里。
可以在窗口引用中傳遞一個function
,但是chrome安全設置可能會干擾本地文件,因為“源安全主體相同”,它可以在本地的其他瀏覽器中使用,但不能在服務器頁面和擴展名中使用,因此值得測試,請遵循以下示例:
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>
輸出將是一個新窗口,其中包含“屬性已轉移”。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.