Google Chrome extensions document.title not working

六月ゝ 毕业季﹏ 提交于 2020-01-03 16:58:38

问题


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.


回答1:


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.




回答2:


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';



回答3:


Try this:

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


来源:https://stackoverflow.com/questions/7655608/google-chrome-extensions-document-title-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!