简体   繁体   中英

chrome.tabs.executeScript doesn't work in chrome.tabs.create callback

chrome.tabs.create({
    url: "about:blank"
}, function (tab) {
    chrome.tabs.executeScript(tab.id, {
        code: "window.setTimeout(function() {document.write(\"123\")},5000);"
    })
});

I'm writing a simple chrome plugin and want to open a new tab that only contains "123". I'm already using setTimeout to ensure that the code runs after loading, but "123" won't be written. What am I doing wrong?

You cannot run any content scripts on about:blank ( bug 55084 , bug 76429 ).

If you want to display information in a new tab, either use a data: -URL,

chrome.tabs.create({
    url: "data:text/html,<script>" + 
         "window.setTimeout(function() {document.write(\"123\")},5000);" +
         "</script>"
});

or a page within your Chrome extension (note: chrome.tabs.executeScript cannot be used to run content scripts on chrome-extension: -URLs either):

chrome.tabs.create({
    // TODO: Create a file called view.html that renders the result
    url: chrome.runtime.getURL("view.html")
});

view.html is subject to the CSP , so if you want to use scripts, it must be put in a separate file:

<!-- view.html -->
<script src="view.js"></script>
// view.js
window.setTimeout(function() {document.write("123")},5000);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM