douzhu1188
douzhu1188
2015-06-05 04:05

从Contentscript.js插入代码(Chrome扩展程序)

已采纳

I am Developing the Politics & Information Google Chrome Extension but I have run into a problem, I am attempting to insert a JS Script into one of the div's of the Webpage, the result is nothing, absolutely nothing pops up

I know i have the right area because if I use += "Hello"; it displays the text there properly, but when I actually do +="" the script doesn't seem to run. To all them devs out there, any suggestions?

How I am doing it:

theinfotable.children[0].innerHTML += ''; JavaScript (Google Chrome Extension inserted from the Contentscripts.js file)

I can see that the Code Inserted, but the script still doesn't seem to load: (And I know this code works when I have my own page instead of inserting) http://oi61.tinypic.com/2irkx9c.jpg

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

2条回答

  • douaoren4402 douaoren4402 6年前

    I figured out the problem, the page was blocking my script as "Insecure" at the top right there was a little Shield Icon and after clicking on it I just had to put "Show Insecure Scripts" and it popped up.

    (If anyone feels like telling me so people don't have to do this, that'd be great :D) I would rather people just have it pop up instead of having to stay for it to pop up

    点赞 评论 复制链接分享
  • doumianfeng5065 doumianfeng5065 6年前

    Rather than use .innerHTML, have you tried creating a new element and appending it?

    var injectable = document.createElement("script");
    injectable.innerHTML = "console.log('Injected!');" // Your script here
    // or injectable.src = "location" if you'd rather link
    theinfotable.children[0].appendChild(injectable);
    

    I'm not entirely sure why this occurs, if I had to guess it's an idiosyncrasy in how things are parsed or a security measure, but appendChild should do the trick. Basically, from what I understand it's the difference between

    innerHTML +=: converting HTML to a string, and adding to that string, and re-parsing that string with new content

    and...

    appendChild: creating a DOM node, appending said DOM node, recalculating/refreshing the document for styling recalculations.

    And somewhere in the parsing, your new script info is ignored.

    点赞 评论 复制链接分享