크롬 스토리지 동기화 값 입력

0

질문

보를 얻을 입력 값에서 나 main.js (스크립트의 콘텐츠)하지만 나는 투쟁 finialize 어떻게든 그것. I maged 값을 저장하려면,매우 위험합니다.onload 접근법 당신이 볼 수 있는 아래에 나 popup.js. 그러나 나는 그것을 얻을 수 없습을 통해 컨텐츠 스크립트입니다. 내가 값을 사용하려는 변수로"userInput"내 콘텐츠에서 스크립트입니다.

popup.js:

function registerButtonAction(tabId, button, action) {
    // clicking button will send a message to
    // content script in the same tab as the popup
    button.addEventListener('click', () => chrome.tabs.sendMessage(tabId, { [action]: true }));
}

function setupButtons(tabId) {
    // add click actions to each 3 buttons
    registerButtonAction(tabId, document.getElementById('start-btn'), 'startSearch');
    registerButtonAction(tabId, document.getElementById('deals-btn'), 'startDeals');
    registerButtonAction(tabId, document.getElementById('stop-btn'), 'stopSearch');
}

function injectStartSearchScript() {
    chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
        // Injects JavaScript code into a page
        // chrome.tabs.executeScript(tabs[0].id, { file: 'main.js' });

        // add click handlers for buttons
        setupButtons(tabs[0].id);
    });
}

injectStartSearchScript();

window.onload = function () {
    document.getElementById('save-btn').onclick = function () {
        let valueInput = document.getElementById('deal-ipt').value;

        chrome.storage.sync.set({ 'maxBidDeal': valueInput }, function () {
            alert('Saved!');
        });
    };
};

manifest.json:

{
    "manifest_version": 2,
    "name": "test app",
    "description": "test desc",
    "version": "1.0",
    "browser_action": {
        "default_icon": "icon.png",
        "default_popup": "popup.html"
    },
    "permissions": ["tabs", "<all_urls>", "storage"],
    "content_scripts": [
        {
            "matches": ["<all_urls>"],
            "js": ["main.js"]
        }
    ],
    "content_security_policy": "script-src 'self' https://ajax.googleapis.com; object-src 'self'"
}

main.js:

function startSearch() {
// does soemthing
}

function deals() {
// here is my variable userInput
userInput = 
}

chrome.runtime.onMessage.addListener((message) => {
    // choose action based on received message:
    if (message.startSearch) {
        startSearch();
    } else if (message.startDeals) {
        deals();
    }
});

// sanity check: content has loaded in the tab
console.log('content loaded');

그래서 나는 확실히 사용하고 있는 겁니다.스토리지.을 얻을 어떻게든지 그것을 파악니다.

1

최고의 응답

1

코드는 전화 deals 재귀적으로 영원히 없이 실제로 전달하는 값지 않았기 때문에 당신은 매개 변수를 선언하고 그런 다음 사용하려 userinput 을 넘어 변수의 범위가 있습니다.

할 수 있습 promisify chrome.storage 고 사용 await 다음과 같다:

async function deals() {
  // Note that chrome.storage is already promisified in ManifestV3 since Chrome 95 
  let { MaxBidDeal } = await new Promise(resolve =>
    chrome.storage.sync.get('MaxBidDeal', resolve));

  // use MaxBidDeal right here
  console.log('MaxBidDeal', MaxBidDeal);
}
2021-10-25 19:38:39

면 사본을 붙여넣기 ur 코드를 컨텐츠 스크립트가 이것을 얻을: Uncaught (in promise) TypeError: Error in invocation of storage.get(optional [string|array|object] keys, function callback): No matching signature.
exec85

아아,미안,당신은 당신을 사용하여 ManifestV2 참조하십시오 업데이트한 대답합니다.
wOxxOm

말할 수 없습 덕분에 충분합니다.... 작동:-)양해 해 주셔서 감사합니다! 나는 그냥 learing JS 고 배우려고 크롬 확장 프로젝트와는 나에게 너무 많은 두통...
exec85

다른 언어로

이 페이지는 다른 언어로되어 있습니다

Русский
..................................................................................................................
Italiano
..................................................................................................................
Polski
..................................................................................................................
Română
..................................................................................................................
हिन्दी
..................................................................................................................
Français
..................................................................................................................
Türk
..................................................................................................................
Česk
..................................................................................................................
Português
..................................................................................................................
ไทย
..................................................................................................................
中文
..................................................................................................................
Español
..................................................................................................................
Slovenský
..................................................................................................................