[英]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.