简体   繁体   中英

Google Chrome extensions document.title not working

here is the code in the manifest.json

{
  "name": "Page Title changer",
  "version": "1.0",
  "description": "Change the <title></title> of a page",
  "browser_action": {
    "default_icon": "icon.png"
  },
  "content_scripts": [
    {
      "matches": ["http://*/*"],
      "js": ["changetitle.js"]
    }
  ]
}

and here is the code from the changetitle.js file

chrome.browserAction.onClicked.addListener(function() {
    document.title = 'new page title';
});

i don't understand why it isn't working, i checked the google code docs while writing this extension.

As detailed in the documentation you cannot use chrome.* API within content scripts except for some chrome.extension.* methods.

However, this doesn't really limit you as you can use messaging to call your content script from your background page. For example;

background.html

<script type="application/javascript">
chrome.browserAction.onClicked.addListener(function() {
    chrome.tabs.getSelected(function (tab) {
        chrome.tabs.sendRequest(tab.id, {title: 'new page title'}, function (response) {});
    });
});
</script>

changetitle.js

chrome.extension.onRequest.addListener(function (request, sender, sendResponse) {
    document.title = request.title;
});

You will of course require the tabs permission in order to use this technique.

This one will work in any URI Scheme

manifest.json

{
  "name": "Page Title changer",
  "version": "1.0",
  "description": "Change the <title></title> of a page",
  "browser_action": {
    "default_icon": "icon.png"
  },
  "background_page": "background.html",
  "permissions": [
        "tabs"
  ]
}

background.html

chrome.browserAction.onClicked.addListener(function () {
    chrome.tabs.executeScript(null, {
        file: "changetitle.js"
    });
});

changetitle.js

document.title = 'new page title';

Try this:

chrome.browserAction.onClicked.addListener(function () {
    chrome.tabs.executeScript(null, {
        code: "document.title = 'new page title'"
    });
});

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