开发者

append html elements to DOM by background script

开发者 https://www.devze.com 2023-03-27 03:55 出处:网络
I want to append the same html elements to the current TAB\'s document DOM. I want these html extended elements to live \"forever\", so I want to built them once, and append them on every page load by

I want to append the same html elements to the current TAB's document DOM. I want these html extended elements to live "forever", so I want to built them once, and append them on every page load by the content script.

I was thinki开发者_StackOverflow中文版ng to place the createElement commends at the background page. Then for every web page load, I want the content script to communicate with the background script, so it will append them to the current TAB document DOM. Is that good practice? My problem is that I don’t know how to append html elements to the DOM from the background page. Can you please help?


This cannot work. The background page lives in one process, the tab in the other - you cannot send objects from one to the other, only text data (objects sent are automatically converted to JSON). So your best chance is: build everything together in the background page, then get innerHTML of your element and send this text to the content script whenever necessary. The content script should then create a new element and set its innerHTML to the value it received.


You need to do it in content script because "content scripts" are scripts which run in an environment between a page and the Chrome extension. see this. remember these scripts will loaded on every page load and they won't affect already opened tabs. as an example you can add external scripts like this

var theScript = document.createElement('script');
theScript.src = "http://mybwesite.com/static/js/myscript.js"
document.body.appendChild(theScript);

as long as you've added it's permissions in manifist:

"permissions": [
     "activeTab",
     "tabs",
      "http://*/*", "https://*/*"
  ],
  "content_scripts": [
      {
        "matches": ["<all_urls>"],
        "js": ["js/contentscript.js"]
      }
    ]
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号