2012-05-16 34 views
0

我试图获得登录代码在后台页面浏览器的启动只运行一次运行。但似乎在bgpage全局代码运行,每上弹出点击时。它也运行在不同的范围。有没有可能解决这个问题?后台代码的任何弹出窗口点击

// background.js 
var someCustomType = new SomeCustomType(); 

function SomeCustomType() { 
    this.firstProperty; 
} 

function thisShouldBeCalledOnce() { 
    someCustomType.firstProperty = 'defined'; 
    alert('someCustomType.firstProperty=' + someCustomType.firstProperty); 
    console.log('thisShouldBeCalledOnce'); 
} 

if (true) { 
    // Alwase 'undefined' 
    alert('someCustomType.firstProperty=' + someCustomType.firstProperty); 
    thisShouldBeCalledOnce(); 
} 

回答

0

简单的代码示例:

manifest.json的

{ 
    "name": "My First Extension", 
    "version": "1.0", 
    "manifest_version": 2, 
    "description": "The first extension that I made.", 
    "browser_action": { 
    "default_icon": "icon.png", 
    "default_popup": "popup.html" 
    }, 
    "background": { 
    "scripts": ["background.js"] 
    }, 
    "permissions": [ 
    "tabs", 
    "http://*/*", 
    "https://*/*" 
    ] 
} 

popup.html:只是一些虚拟代码:

<html> 
<head> 
</head> 
<body> 
<div> 
    <p> sometext</p> 
    <button type="button">Click Me</button> 
</div> 
</body> 
</html> 

BAC kground.js:

var someCustomType = new SomeCustomType(); 
function SomeCustomType() { 
    this.firstProperty; 
} 
function thisShouldBeCalledOnce() { 
    someCustomType.firstProperty = 'defined'; 
    alert('someCustomType.firstProperty=' + someCustomType.firstProperty); 
    console.log('thisShouldBeCalledOnce'); 
} 
thisShouldBeCalledOnce(); 

在这种情况下,警报被触发一次,当你加载你的扩展,当打开弹出任何警报将显示你。问候。

+0

真的,我发现我的错误,'<脚本类型= “文/ JavaScript的” SRC = “JS/background.js”>'是'popup.html' – Vasya