此代码是Chrome扩展程序的一部分。
的manifest.json
{
"name": "BrowserExtension",
"version": "0.0.1",
"manifest_version": 2,
"description" : "Description ...",
"browser_action": {
"default_icon": "icon.png",
"default_popup": "popup.html"
},
"background": {
"scripts": ["background.js"],
"persistent": false
},
"permissions": ["*://*.google.com/", "tabs", "activeTab", "*://*.facebook.com/"],
"content_scripts": [{
"matches": ["http://*/*","http://*/", "https://*.facebook.com/","https://*/*"],
"js": ["content.js"]
}]
}
popup.html
<body>
<pre>
<input type="button" value="Get Password" id="link">
</pre>
<script type="text/javascript" src="content.js"></script>
</body>
content.js
{
window.open("https://www.facebook.com");
var myUsername = 'ABCD';
var myPassword = 'password';
var loginField = document.getElementById('email');
var passwordField = document.getElementById('pass');
loginField.value = myUsername;
passwordField.value = myPassword;
}
如果我保留此代码而不将其封装在任何函数中,那么如果我打开facebook.com,那么我可以找到设置在相应字段中的值。 但是,如果我将Content.js更改为:
var x = document.getElementById("link");
x.addEventListener("click", myFunction);
function myFunction()
{
alert("content.js Started .. ");
window.open("https://www.facebook.com");
var myUsername = 'ABCD';
var myPassword = 'password';
var loginField = document.getElementById('email');
var passwordField = document.getElementById('pass');
loginField.value = myUsername;
passwordField.value = myPassword;
}
然后点击按钮,Facebook正在打开,但字段未设置。即使代码在功能块中,我也希望能够做到这一点。