2017-07-27 202 views
0

我正在爲自己的用途創建一個擴展,但我遇到了問題。我想爲background.jscontent.js分配一個變量值。儘管刷新了內容頁面,但始終存在background.js的變量。這個怎麼做?如何從內容腳本訪問後臺腳本變量

的manifest.json

{ 

    "manifest_version": 2, 
    "name": "Slownik", 
    "version": "1.0", 

    "description": "Slownik", 

    "background": { 
    "scripts": ["background.js"] 
    }, 

    "content_scripts": [ 
    { 
     "matches": ["*://*.sjp.pl/*"], 
     "js": ["content.js"] 
    } 
    ] 
} 

background.js

var test = "test"; 

content.js

test = "testA"; 

回答

3

另一種方法是使用browser.runtime.sendMessage() API。

在內容腳本:

document.addEventListener('DOMContentLoaded', function() { 
    browser.runtime.sendMessage({ 
     type: "getText" 
    }).then(function(message) { 
     console.log("Value of text is: ", message.result); 
    }); 

    browser.runtime.sendMessage({ 
     type: "setText", 
     value: "Yes, I can get you!!" 
    }).then(function(message) { 
     console.log("New value of text is: ", message.result); 
    }); 
}); 

在後臺腳本:

var text = "Can you get me??"; 

browser.runtime.onMessage.addListener(function(request, sender, sendResponse) { 
    if (request.type == "getText") { 
     sendResponse({result: text}); 
    } else if (request.type == "setText") { 
     text = request.value; 
     sendResponse({result: text}); 
    } 
}); 

在瀏覽器控制檯,我們可以看到輸出:

Value of text is: Can you get me?? 
New value of text is: Yes, I can get you!! 
1

究竟是什麼你的願望是不可能的。後臺腳本和內容腳本在不同的上下文中執行,在某些情況下執行不同的進程。不可能在兩個環境之間直接共享一個變量。但是,您可以共享信息。

.storage.local存在能夠以所有腳本均可訪問的方式在您的擴展中存儲信息。 存儲在.storage.local中的數據在瀏覽器重新啓動後仍然存在。您可以使用.storage.local.set(),在您的background.js中設置一個值,然後從content.js中使用.storage.local.get()獲取該值。

在上面鏈接的MDN頁面上有使用.storage.local的例子。還有很多Stack Overflow questions/answers which provide examples


1.除插入到頁面上下文中的腳本。這些不是內容腳本,但可以使用內容腳本插入它們。它們是您用於訪問通常在網頁上運行的頁面腳本中存在的變量和函數的內容。

相關問題